如何在multi-catch语句中使用final?

Sha*_*ain 3 java exception

在Java中的单个catch块中捕获多种类型的异常时,如何为异常提供final修饰符

CKi*_*ing 5

您不需要将每个例外标记为最终.只是第一个.

try {

} catch(final IllegalArgumentException  | ArrayIndexOutOfBoundsException e) {
    e = new RuntimeException();//this will not be allowed as e is final
}
Run Code Online (Sandbox Code Playgroud)

话虽这么说,你不需要标记e为final,因为在使用multi-catch语句时无论如何都不能在catch块中重新分配.

这是JLS的相关部分

如果未明确声明final,则多catch子句的异常参数将隐式声明为final.

如果在catch子句的主体内分配了隐式或显式声明为final的异常参数,则为编译时错误.