OOP – ASSIGNMENT X

Lab Manual Download: Write a java program which use try and catch for exception handling.

ASSIGNMENT NO 10

 Title: Demonstrate Exception Handling in Java

Objectives: To learn exception handling in Java.

Problem Statement:  Write a java program which use try and catch for exception handling..

Outcomes: 1) Students will be able to learn and understand exception handling.

2) Students will be able to demonstrate exception handling in Java programs.

Hardware requirements: Any CPU with Pentium Processor or similar, 256 MB RAM or more, 1 GB Hard Disk or more.

Software requirements:  64 bit Linux/Windows Operating System, JDK 1.4 or later

Theory:

An Exception can be anything which interrupts the normal flow of the program. When an exception occurs program processing gets terminated and doesn’t continue further. In such cases we get a system generated error message. The good thing about exceptions is that they can be handled.  Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known Compile-time exceptions).

Reasons for Exceptions:  There can be several reasons for an exception. For example, following situations can cause an exception – Opening a non-existing file, Network connection problem, Operands being manipulated are out of prescribed ranges, class file missing which was supposed to be loaded and so on.

Difference between error and exception:

Errors indicate serious problems and abnormal conditions that most applications should not try to handle. Error defines problems that are not expected to be caught under normal circumstances by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take necessary corrective actions. Few examples –

  1. DivideByZero exception
  2. NullPointerException
  3. ArithmeticException
  4. ArrayIndexOutOfBoundsException

Advantages of Exception Handling

Exception handling allows us to control the normal flow of the program by using exception handling in program. It throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error. It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks.

Why to handle exception?

If an exception is raised, which has not been handled by programmer then program execution can get terminated and system prints a non user friendly error message.

Ex:-Take a look at the below system generated exception

An exception generated by the system is given below

Exception in thread “main” java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:5)

ExceptionDemo : The class name

main : The method name

ExceptionDemo.java : The filename

java:5 : Line number

For a novice user the above message won’t be easy to understand. In order to let them know that what went wrong we use exception handling in java program. We handle such conditions and then prints a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user.

exception-classes-hierarchy

Java Exception Handling Keywords: There are 5 keywords used in java exception handling.

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

Java try block: Java try block is used to enclose the code that might throw an exception. It must be used within the method. Java try block must be followed by either catch or finally block.

Syntax of java try-catch

try{

//code that may throw exception

}catch(Exception_class_Name ref){}

Syntax of try-finally block

try{

//code that may throw exception

}finally{}

Java catch block: Java catch block is used to handle the Exception. It must be used after the try block only. You can use multiple catch block with a single try.

Java Multi catch block: If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block. Let’s see a simple example of java multi-catch block.

public class TestMultipleCatchBlock{

public static void main(String args[]){

try{

int a[]=new int[5];

a[5]=30/0;

}

catch(ArithmeticException e){System.out.println(“task1 is completed”);}

catch(ArrayIndexOutOfBoundsException e){System.out.println(“task 2 completed”);}

catch(Exception e){System.out.println(“common task completed”);}

System.out.println(“rest of the code…”);

}

}

Output:

task1 completed

rest of the code…

Java Nested try block: The try block within a try block is known as nested try block in java.

Why use nested try block: Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:

….

try

{

statement 1;

statement 2;

try

{

statement 1;

statement 2;

}

catch(Exception e)

{

}

}

catch(Exception e)

{

}

….

Java nested try example: Let’s see a simple example of java nested try block.

class Excep6{

public static void main(String args[]){

try{

try{

System.out.println(“going to divide”);

int b =39/0;

}catch(ArithmeticException e){System.out.println(e);}

try{

int a[]=new int[5];

a[5]=4;

}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println(“other statement);

}catch(Exception e){System.out.println(“handeled”);}

System.out.println(“normal flow..”);

}

}

 Conclusion : In this assignment, we have studied exception handling in Java and demonstrated use of try-catch block in program.

Roll No. Name of Student Date of Performance Date of Assessment Grade Sign of Student Sign of Faculty
 

 

PROGRAM

class ExceptionDemo1 {
 public static void main(String args[])
 {
 //Display Menu to enter your choice
 System.out.println("****************MENU******************");
 System.out.println("1. Add\n2. Sub\n3. Mul\n4. Div\n5. Mod");
 System.out.println("Enter you choice");
 int choice=Integer.parseInt(System.console().readLine());
 //Read two number from user and convert numeric string in to integer
 System.out.println("Enter number 1 and number 2");
 int num1=0,num2=0;
 try
 {
 num1=Integer.parseInt(System.console().readLine());
 num2=Integer.parseInt(System.console().readLine());
 }
 catch(NumberFormatException e)
 {
 System.out.println(e);
 System.out.println("Only Numeric String is allowed. Exiting program");
 System.exit(1);
 }
 int result=0;
 //check choice entered by user and perform operation
 switch(choice)
 {
 case 1:
 result=num1+num2;
 break;
 case 2:
 result=num1-num2;
 break;
 case 3:
 result=num1*num2;
 break;
 case 4:
 try
 {
 result=num1/num2;
 }
 catch(ArithmeticException e)
 {
 System.out.println(e);
 System.out.println("Can not divide a number by zero.Assigning 1 to result");
 result=1;
 }
 break;
 case 5:
 result=num1%num2;
 break;
 default:
 System.out.println("Wrong choice");
 System.exit(0);
 }
 //Display result
 System.out.println("Result is "+result);
 
 }
}

OUTPUT:

ass-10-op1ass-10-op2

Leave a Reply

Your email address will not be published. Required fields are marked *