Friday 12 January 2018

Can I catch multiple Java exceptions in the same catch clause?

itemprop="text">

In Java, I want to do something like
this:




try {

...
} catch (/* code to catch IllegalArgumentException, SecurityException,

IllegalAccessException, and NoSuchFieldException at the same time */)
{

someCode();
}


...instead
of:




try {

...
} catch (IllegalArgumentException e) {
someCode();
}
catch (SecurityException e) {
someCode();
} catch
(IllegalAccessException e) {
someCode();
} catch
(NoSuchFieldException e) {


someCode();
}


Is
there any way to do this?


itemprop="text">
class="normal">Answer



This has
been possible href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html"
rel="noreferrer">since Java 7. The syntax for a multi-catch block
is:



try { 

...

} catch (IOException | SQLException ex) {

...
}


Remember,
though, that if all the exceptions belong to the same class hierarchy, you can simply
catch that base exception type.



Also note that
you cannot catch both ExceptionA and ExceptionB in the same block if ExceptionB is
inherited, either directly or indirectly, from ExceptionA. The compiler will
complain:



Alternatives in a multi-catch statement cannot be
related by subclassing

Alternative ExceptionB is a subclass of
alternative ExceptionA


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...