java代码无法编译器,Java无法访问的catch块编译器错误

Why in Java can we catch an Exception even if it is not thrown, but we can't catch it's subclass (except for "unchecked" RuntimeExceptions and it subclasses). Example code:

class Test {

public static void main(String[] args) {

try {

// do nothing

} catch (Exception e) {

// OK

}

try {

// do nothing

} catch (IOException e) {

// COMPILER ERROR: Unreachable catch block for IOException.

//This exception is never thrown from the try statement body

}

}

}

Any ideas?

解决方案

A RuntimeException could be thrown by any code. In other words, the compiler can't easily predict what kind of code can throw it. A RuntimeException can be caught by a catch(Exception e) block.

IOException, however, is a checked exception - only method calls which are declared to throw it can do so. The compiler can be (reasonably) confident that it can't possible occur unless there are method calls which are declared to throw it.

The Java compiler simply doesn't consider the "there's no code at all within the try block" situation - it always allows you to catch unchecked exceptions, as in all reasonable scenarios there will be code which could potentially throw an unchecked exception.

From section 14.21 of the JLS:

A catch block C is reachable iff both of the following are true:

Some expression or throw statement in the try block is reachable and can throw an exception whose type is assignable to the parameter of the catch clause C. (An expression is considered reachable iff the innermost statement containing it is reachable.)

There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.

Arguably the compiler should realize that there are no expressions within the try block in your first case... it looks like this is still an unreachable catch clause, to me.

EDIT: As noted in comments, section 14.20 contains this:

It is a compile-time error if a catch clause catches checked exception type E1 but there exists no checked exception type E2 such that all of the following hold:

E2 <: e1>

The try block corresponding to the catch clause can throw E2

No preceding catch block of the immediately enclosing try statement catches E2 or a supertype of E2.

unless E1 is the class Exception.

So it looks like that's what you're actually running foul of, but the spec isn't as clear as it could be in terms of unreachable catch blocks in 14.21.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值