World's most popular travel blog for travel bloggers.

Catching Multiple Exceptions

, , No Comments
Before Java 7, we used to catch multiple exceptions one by one as shown below.
catch (IOException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
catch (SQLException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
}
In Java 7, we can catch both these exceptions in a single catch block as:
catch(IOException | SQLException ex){
     logger.error(ex);
     throw new MyException(ex.getMessage());
}
If a catch block handles multiple exception, you can separate them using a pipe (|) and in this case exception parameter (ex) is final, so you can’t change it. The byte code generated by this feature is smaller and reduce code redundancy.

0 comments:

Post a Comment

Let us know your responses and feedback