Pages

Friday, February 9, 2018

How to catch multiple Java Exceptions with same catch

How to catch multiple Java Exceptions with same catch
 
In Older versions of Java, There are chances like, the same method would throw multiple exceptions.
Either you can use java.lang.Exception  ( Since all Exceptions extends java.lang.Exception) to catch the exceptions. But the issue will be even some unexpected Exceptions would be caught. For example, We would be expecting a FileNotFoundException, but would have a NullPointerException being caught. To analyze the exception then we need to use instanceof keyword. Again this is painful and we will be doing the redundant .

Other way is to have multiple catch clause, again this will make the code lengthier.

To avoid these issues, in Java 7 , Multiple Exception catch clause is introduced.

try { 
  ...
} catch (IOException | SQLException ex) { 
  ...
}
 
Solution:
https://stackoverflow.com/questions/3495926/can-i-catch-multiple-java-exceptions-in-the-same-catch-clause
 

No comments:

Post a Comment