Java Catching Multiple Exception

Consider following multiple catch blocks – Below example contain two catch blocks having two exceptions (i.e IOException and SQLException)

Catching Multiple Exception in single catch :

Whenever try block will thrown any exception of these type then and then only we can handle the exception.

catch (IOException ex) {
     System.out.println("IO Exception");
     throw ex;
} catch (SQLException ex) {
     System.out.println("SQL Exception");
     throw ex;
  1. If in a try block we need to handle multiple exceptions then we need to write exception handler for each type of exception.
  2. We can combine the multiple exceptions in catch block using Pipe (|) Operator.
catch (IOException|SQLException ex) {
    System.out.println("Exception thrown");
    throw ex;

above single catch block can handle IO as well as SQL exceptions. So it is better to use Pipe Operator to handle multiple exceptions instead of writing individual catch block for each exception. Also Refer this oracle guide for more information.

Parameter Accepted by Catch Block is Final :

  1. If a catch block handles more than one exception type, then the catch parameter is implicitly final.
  2. In this example, the catch parameter ex is final.
  3. We cannot assign any values to it within the catch block.

[box style=” light-yellow warning rounded shadow”]
Note :We can use Pipe (|) to catch multiple exceptions only in Java SE 7 or in higher versions.