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();
- public class Testtrycatch2{
- public static void main(String args[]){
- try{
- int data=50/0;
- }catch(ArithmeticException e){System.out.println(e);}
- System.out.println("rest of the code...");
- }
- }
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...");
}
}