The multiple catch blocks can generate unreachable code error i.e. if the first catch block contains the Exception class object then the subsequent catch blocks are never executed. This is known as Unreachable code problem.
Example:
try{
System.out.println(3/0); //here arithmetic exception has come
System.out.println(“Pls. print me.”);
}catch( Exception e){
System.out.println(“Exception 1.”);
}
catch(ArithmeticException e1){ //here unreachable code problem has come. Compilation error
System.out.println(“Exception e2”);
}
}
}
To avoid this, the last catch block in multiple catch blocks must contain the generic class object that is called the Exception class. This exception class being the super class of all the exception classes and is capable of catching any types of exception. The generic Exception class can also be used with multiple catch blocks.
Example:
try{
System.out.println(3/0); //here arithmetic exception has come
System.out.println(“Pls. print me.”);
}catch( ArithmeticException e){
System.out.println(“Exception 1.”);
}
catch(Exception e1){ //OK
System.out.println(“Exception e2”);
}
}
}
0 comments:
Post a Comment