开发者

How to manage catches with the same behavior

开发者 https://www.devze.com 2023-03-19 06:16 出处:网络
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 goo

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*/ }
0

精彩评论

暂无评论...
验证码 换一张
取 消