Google+

225. Order of catch blocks








Pre-requisite -


All the catch blocks must be ordered from most specific to most generic. Arithmetic Exception thrown by int a= 1/0; can be handled by the most specific 'ArithmeticException' Class or most generic 'Exception' class as shown in the below example -

try
{
      int a=1/0; //Throws Arithmetic Exception
}

catch(ArithmeticException object1)
{
       System.out.println("Handled by ArithmeticException Class");
}

catch(Exception object2)
{
      System.out.println("Handled by Exception Class");
}

Output

On executing the above example, the program will run without any errors, as the most specific 'ArithmeticException' Class is before the most generic 'Exception' Class.
Placing most generic Exception Class before most specific ArithmeticException Class -

Compile time error will be displayed in the program code when the catch blocks are ordered from most generic to most specific. Example - When catch block having 'Exception' Class is before the catch block having 'ArithmeticException' Class.

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a Java Class 'OrderOfExceptions.java' with main( ) method  in the existing project 'Project 46' as shown below -



2. Write a statement which throws Arithmetic Exception in try block as shown below -



3. Handle the exception catch blocks by placing the catch blocks in wrong order (i.e. from more generic to more specific) and observe that a compile time error is displayed as shown below - 


4. View the error message a shown below -


5. Lest resolve the above compile time error by changing the order of catch blocks (i.e. lets order from more specific to more generic) and observe that the error got resolved -



6. Save and Run the 'OrderOfExceptions.java' Class, observe that the the thrown exception from try block is handled by the more specific ArithmeticException Class in first catch block and the output is displayed as shown below  -








Please comment below to feedback or ask questions.

Handling Exceptions using Exception Class for safe side will be explained in the next post.






No comments: