I have a piece of code that can throw three different types of exceptions. Two of these exceptions are handled in a cer开发者_开发问答tain 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*/ }
Java 6 doesn't support specifying catch blocks this way. Your best bet would be to define a super-class/interface for those two exception types and catch the super-class/interface. Another simple solution would be to have a method which contains the logic for handling those two exceptions and call that method in the two catch blocks.
How about defining a custom Exception (let's say DException
) that extends both AException
and BException
, then use it in your code:
try { anObject.dangerousMethod(); }
catch {DException e) { /*do something*/ }
catch {CException e) { /*do something else*/ }
精彩评论