Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use final in a multi-catch statement?

Tags:

java

exception

How to give final modifier to the exception when catching multiple type of exceptions in a single catch block in Java

like image 285
Shaik Zakir Hussain Avatar asked Feb 12 '26 07:02

Shaik Zakir Hussain


2 Answers

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.

like image 139
Chetan Kinger Avatar answered Feb 14 '26 23:02

Chetan Kinger


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 final if it is not explicitly declared final.

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.

like image 23
Marko Topolnik Avatar answered Feb 14 '26 21:02

Marko Topolnik