Java Tutorial 23 – Exception Hierarchy

In case there are multiple exceptions that might arise in a try block, you can provide several catch blocks each handling a different type of exception.

Syntax:-

try{
statement(s)
}
catch (exceptiontype name){
}
catch (exceptiontype name){
}
catch (exceptiontype name){
}
catch (exceptiontype name){
}

After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.The nested catch blocks follow Exception hierarchy. The following video introduces the Java Exception Hierarchy.

Please be patient . Video will load in some time. If you still face issue viewing video click here

Assignment: To understand nesting of try and catch blocks

Step 1) Copy the following code into an editor

class JavaException {
public static void main(String args[]){
try{
int d =1;
int n =20;
int fraction = n/d;
int g[] ={1} ;
g[20] =100;
}
/*catch(Exception e){
System.out.println("In the catch clock due to Exception = "+e);
}*/
catch(ArithmeticException e){
System.out.println("In the catch clock due to Exception = "+e);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("In the catch clock due to Exception = "+e);
}
System.out.println("End Of Main");
}
}

Step 2) Save the file  & compile the code. Run the program using command, java JavaException.
Step 3) An ArrayIndexOutOfBoundsException is generated. Change the value of int d =1. Save ,Compile & Run the code. 
Step 4)  An ArithmeticException must be generated.
Step 5) Uncomment line #10 to line #12 . Save , Compile & Run the code.
Step 6) Compilation Errror ? This is because Exception is the base class of ArithmeticException Exception. Any Exception that is raised by ArithmeticException can be handled by Exception class as well .So the catch block of ArithmeticException will never get a chance to be executed which makes it redundant. Hence the compilation error.