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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With