Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage catches with the same behavior

Tags:

java

exception

I have a piece of code that can throw three different types of exceptions. Two of these exceptions are handled in a certain way while the third is handled in another way. Is there a good idiom for not cutting and pasting in this manner?

What I would like to do is:

try { anObject.dangerousMethod(); }
catch {AException OR BException e) { /*do something*/ }
catch {CException e) { /*do something else*/ }
like image 679
Amir Rachum Avatar asked Jan 19 '23 06:01

Amir Rachum


2 Answers

There is in JDK 7, but not in earlier Java versions. In JDK 7 your code could look like this:

try { anObject.dangerousMethod(); }
catch {AException | BException e) { /*do something*/ }
catch {CException e) { /*do something else*/ }
like image 181
Martin Avatar answered Feb 01 '23 15:02

Martin


As defined by new Java 7 specifications you can now have.

try { anObject.dangerousMethod(); }
catch {AException | BException e) { /*do something*/ }
catch {CException e) { /*do something else*/ }
like image 41
Nican Avatar answered Feb 01 '23 16:02

Nican