Tuesday, April 24th
Exception Handling

 

What to do when exceptions are thrown - catch them 
try{ this part of the program might throw an exception }
catch (exception e){
this code will execute if the code in the try block throws an exception.
this code will handle the exception }

finally {

Common exceptions - also note the exceptions heirachy - exceptions are objects and are subclasses of the Throwable class. Two useful methods are getMessage() and printStackTrace();

  1. public class Testtrycatch2{  
  2.   public static void main(String args[]){  
  3.    try{  
  4.       int data=50/0;  
  5.    }catch(ArithmeticException e){System.out.println(e);}  
  6.    System.out.println("rest of the code...");  
  7. }  
  8. }  

Sample use of mutliple catch statements:

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...");
}
}