How to give final modifier to the exception when catching multiple type of exceptions in a single catch block in Java
You don't need to mark every exception as final. Just the first one.
try {
} catch(final IllegalArgumentException | ArrayIndexOutOfBoundsException e) {
e = new RuntimeException();//this will not be allowed as e is final
}
That being said, you don't need to mark e as final as it cannot be reassgined in the catch block either way when using a multi-catch statement.
Here's the relevant section of the JLS
An exception parameter of a multi-catch clause is implicitly declared final if it is not explicitly declared final.
It is a compile-time error if an exception parameter that is implicitly or explicitly declared final is assigned to within the body of the catch clause.
The following is aimed to provide the authoritative answer.
Java Language Specification, Java SE 7 Edition, §14.20:
An exception parameter of a multi-catch clause is implicitly declared
finalif it is not explicitly declaredfinal.
As for the syntax:
CatchClause:
catch ( CatchFormalParameter ) Block
CatchFormalParameter:
VariableModifiersopt CatchType VariableDeclaratorId
This means that you can apply a single final in front of the catch type (which, in the case of multi-catch, is specified as a union of individual exception types). Your confusion may be with the fact that a multi-catch does not contain several, but just one catch variable declaration.
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