Phoenix
Phoenix

Reputation: 8933

Is it a good idea in Java to OR exceptions in catch block?

Should we OR exceptions like this ?

catch (final CustomExceptionA | CustomExceptionB e) {

       Should we catch expections like this ? 
    }

Upvotes: 0

Views: 72

Answers (2)

TwoThe
TwoThe

Reputation: 14309

In Java versions before 7 there was always the issue that if you had to catch multiple exceptions, but (i.E.) only needed to log them, you had to duplicate a lot of code. Example Java 6:

} catch (NullpointerException e) {
  log(e);
} catch (ArrayIndexOutOfBoundsException e) {
  log(e);
} catch (NumberFormatException e) {
...

In Java 7 you can use the | operator to simplify this and - the important part - only have to write the error-handling code once, which will avoid common bugs like copy & paste or similar.

Upvotes: -1

Buddy
Buddy

Reputation: 11038

It's a fine way to do it if you want to handle them in the exact same way. It'll also only compile on Java 7 (and above).

Upvotes: 6

Related Questions