java抛异常final_java – 捕获异常时是否有理由不使用final关键字?

The Java Language Specification 11.2.2在最终和非最终例外之间有所区别:

A throw statement (§14.18) whose thrown expression has static type E and is not a final or effectively final exception parameter can throw E or any exception class that the thrown expression can throw.

[…]

A throw statement whose thrown expression is a final or effectively final exception parameter of a catch clause C can throw an exception class E iff:

E is an exception class that the try block of the try statement which declares C can throw; and

E is assignment compatible with any of C’s catchable exception classes; and

E is not assignment compatible with any of the catchable exception classes of the catch clauses declared to the left of C in the same try statement.

In a uni-catch clause, an exception parameter that is not declared final (implicitly or explicitly) is considered effectively final if it never occurs within its scope as the left-hand operand of an assignment operator.

换句话说,如果你不重新分配你的catch语句的e(如e = new SomeOtherException();),它被隐式声明为final。

所以我只能得出结论,它没有什么区别,除非在catch块中修改异常,唯一可以想出的例子是:

public void method1() throws IOException {

try {

throw new IOException();

} catch (Exception e) { // e is not modified in catch => implicitly final

throw e; //compiles OK

}

}

//it works because method1 is semantically equivalent to method2:

public void method2() throws IOException {

try {

throw new IOException();

} catch (final Exception e) {

throw e;

}

}

public void method3() throws IOException {

try {

throw new IOException("1");

} catch (Exception e) {

e = new IOException("2"); //e modified: not implicitly final any more

throw e; //does not compile

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值