An exception handler designed to handle a specific type of object may be preempted by another handler whose exception type is a super-class of that exception object. This happens if the exception handler for that exception type appears earlier in the list of exception handlers. That is, while using multiple catch statements, it is important to be aware of the order of exception classes and arrange them correctly.
The exception sub-classes must come before any of their super-classes.
If a super-class exception is coded first in the catch block then, when an exception occurs, the super-class exception gets, executed whereas the sub-class exception catch block never gets executed. In Java, this is considered a compile-time error. Hence, the order of the catch blocks is important. Thus, the catch blocks that are written to handle exception types that are far from the root of the hierarchy should be placed first in the list of catch blocks, and the classes nearer to the root must be placed last. That is, the leaves come first and the root is last in the catch block order.
The programmer must take care when providing handlers with exception types at different levels in the inheritance hierarchy.
Look at Program, which gives a compile time error because the general Exception is caught before Arithmetic Exception. Reversing the order of the catch blocks would ensure that the correct exception handler catches the exception. It is important to handle the right exception in the right context.
Program Incorrect ordering of catch blocks.
public class Divide { public static void main (String [] args) { System.out.println ("\n Program Execution starts here\n"); int a, b, c; try { a = Integer.parselnt (args [0]); b = Integer.parselnt (args [1]); c = a/b; System.out.println (a + "/" + b + "=" + c); } catch (ArithmeticException e) { System.out.println ("Exception caught; "+ e); } catch(Exception e) { System.out.println("Second Argument Should not be Zero"); } } }