Multiple catch block in java



Java exception handling allows us to use multiple catch block.

Important Point  about multiple catch block >
  1. Exception class handled in starting catch block must be subclass of Exception class handled in following catch blocks (otherwise we will face compilation error).
  2. Either one of the multiple catch block will handle exception at time.




Here is the syntax for writing multiple catch block >
             try{
                 //code . . . . .
          }catch(IOException ex1){
                 //code . . . . .
          } catch(SQLException ex2){
                 //code . . . . .
          }      


Program - Let’s understand the concept of multiple catch block>
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
   public static void main(String[] args) {
         
          try{
                 int i=10/0; //will throw ArithmeticException
          }catch(ArithmeticException ae){
                 System.out.println("Exception handled - ArithmeticException");
          }catch(RuntimeException re){
                 System.out.println("Exception handled - RuntimeException");
          }catch(Exception e){
                 System.out.println("Exception handled - Exception");
          }         
   }
}
/*OUTPUT
Exception handled - ArithmeticException
*/

In the above above >
ArithmeticException has been used in first catch block
RuntimeException has been used in second catch block
Exception has been used in third catch block

Exception is superclass of RuntimeException and
RuntimeException is superclass of ArithmeticException.


Now, what will happen if RuntimeException is used in first catch and ArithmeticException is used in second catch block.
If RuntimeException would have been used in first catch and ArithmeticException in second catch block then compile time error would have occurred “Unreachable catch block for ArithmeticException. It is already handled by the catch block for RuntimeException”
because in first catch block superclass RunTimeException can handle ArithmeticException, hence making second catch block (i.e. with ArithmeticException) unreachable.
Above code snippet shows compilation error.



Why shouldn’t you use Exception for catching all exceptions in java?
Catching Exception rather than handling specific exception can be vulnerable to our application. Multiple catch blocks must be used to catch specific exceptions, because handling specific exception gives developer the liberty of taking appropriate action and develop robust application.


RELATED LINKS>




EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - detailed explanation with diagrams Set-1 > Q1- Q25


No comments:

Post a Comment