Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific and same actions when catching multiple exceptions

I want to handle exceptions of two different types differently, and after that to make some same actions for both exception types. How to do that in Java?

The following code shows what I want to do, but it is not correct, as one exception can not be caught twice.

What is the right syntax for this?

try {
    // do something...
} 
catch (ExceptionA e) {
    // actions for ExceptionA
}
catch (ExceptionB e) {
    // actions for ExceptionB
}
catch (ExceptionA | ExceptionB e) {
    // actions for ExceptionA & ExceptionB
}
like image 496
Mikhail Batcer Avatar asked Aug 07 '15 13:08

Mikhail Batcer


1 Answers

Use the catch (ExceptionA | ExceptionB e) construct. Within the catch block, first do an instanceof check for e and handle the exception types separately. After this, have the common handling for both types. This way you can do everything in one catch block:

try {
    // do something...
} catch (ExceptionA | ExceptionB e) {
    if (e instanceof ExceptionA) {
        // handling for ExceptionA
    } else {
        // handling for ExceptionB
    }
    // common handling for both exception types
}
like image 79
Mick Mnemonic Avatar answered Nov 07 '22 01:11

Mick Mnemonic