Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

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?

1 Answer

0 votes
by (46k points)

This wasn't possible before Java 7, Use this syntax for Java 7+:

try {

  //.....

} catch ( IllegalArgumentException | SecurityException |

         IllegalAccessException |NoSuchFieldException exc) {

  someCode();

}

It's worth mentioning, that if all the exceptions apply to the same class hierarchy, we can easily catch that base exception type.

And we cannot catch both ExceptionA and ExceptionB in the same block if ExceptionB is inherited, both 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

So you need to take care of it.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...