How to manage catches with the same behavior

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

What I would like to do:

try { anObject.dangerousMethod(); } catch {AException OR BException e) { /*do something*/ } catch {CException e) { /*do something else*/ } 
+4
source share
4 answers

Exists in JDK 7 , but not in earlier versions of Java. In JDK 7, your code might look like this:

 try { anObject.dangerousMethod(); } catch {AException | BException e) { /*do something*/ } catch {CException e) { /*do something else*/ } 
+4
source

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

 try { anObject.dangerousMethod(); } catch {AException | BException e) { /*do something*/ } catch {CException e) { /*do something else*/ } 
+3
source

Java 6 does not support defining catch blocks in this way. It would be best to define a superclass / interface for these two types of exceptions and catch a superclass / interface. Another simple solution would be to have a method that contains logic to handle these two exceptions and call this method in two catch blocks.

+2
source

How to define a custom exception (say DException ) that extends both AException and BException , and then use it in your code:

 try { anObject.dangerousMethod(); } catch {DException e) { /*do something*/ } catch {CException e) { /*do something else*/ } 
0
source

All Articles