Multiple exceptions are caught in a single catch block

in Java7, the catch block has been upgraded to handle multiple exceptions in a single catch block.

code before Java7:

catch (IOException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
catch (SQLException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
}catch (Exception ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

in Java7, we can catch all these exceptions with a catch

catch(IOException | SQLException | Exception ex){
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

if multiple exceptions are handled with a catch block, they can be separated by a pipe, in which case the exception parameter variable ex is defined as final and cannot be modified. This feature will generate less bytecode and reduce code redundancy.

finally welcome to visit my personal website: 1024s

Read More: