Saturday, 22 February 2014

Handling the Exceptions

Java platform provides 3 blocks blocks to handle the exception that may occur in the program.

Those are :
1. try block
2. catch block
3. finally block

Whenever you felt that, there is a possibility of occurring an exception in the code, then place the entire code in the try block. Provide handlers to handle the exception.

After a method throws an exception, the run time system tries to find exception handlers to handle it.

If the Run time system finds a handler to handle the exception, then it executes the block of code in the handler, and Proceed execution from the catch block onwards. Other wise program simply terminates.

Example
class ExceptionEx{
 void print(){
  System.out.println(10/0);
 }

 void callPrint(){
  print();
 }

 public static void main(String args[]){
  ExceptionEx obj = new ExceptionEx();

  try{
   obj.callPrint();
  }

  catch(ArithmeticException e){
   System.out.println("Seems to be an Arithmetic Exception Occurred");
  }
  System.out.println("Finished Execution");
 }
}
 
Output
Seems to be Arithmetic Exception Occurred
Finished Execution

As you observe the output, there is an AirthmeticException occurred, then Java run time system attempts to find out a handler to handle this exception, So it executed the statements inside the catch block. Once the statements in the catch executed, then the statements after the catch statement starts executing.

Exception                                                 try block                                                 Home

No comments:

Post a Comment