I have the following code:
try {
//do some
} catch (NumberFormatException e) {
return DynamicFilterErrorCode.INVALID_VALUE;
} catch (ClassCastException e) {
return DynamicFilterErrorCode.INVALID_VALUE;
} catch (IllegaleArgumentException e) {
return DynamicFilterErrorCode.INVALID_VALUE;
}
Is it possible to combine those 3 catch clauses into one? They have exactly the same handler code, so I'd like to reuse it.
Yes you can have multiple catch blocks with try statement. You start with catching specific exceptions and then in the last block you may catch base Exception . Only one of the catch block will handle your exception. You can have try block without a catch block.
Multiple Catch Block in Java Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in the catch block. Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency.
If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it.
Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.
From Java 7 it is possible :
try {
//do some
} catch (NumberFormatException | ClassCastException | IllegaleArgumentException e) {
return DynamicFilterErrorCode.INVALID_VALUE;
}
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