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*/ }
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*/ }
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*/ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With