Amir Rachum
Amir Rachum

Reputation: 79645

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

Upvotes: 4

Views: 66

Answers (4)

Eng.Fouad
Eng.Fouad

Reputation: 117597

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

Upvotes: 0

Martin
Martin

Reputation: 38289

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

Upvotes: 4

Nican
Nican

Reputation: 7935

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

Upvotes: 3

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23208

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.

Upvotes: 2

Related Questions