【问题标题】:How does that exceprt from the JDK get compiled?JDK 的这段摘录是如何编译的?
【发布时间】:2013-11-17 23:30:57
【问题描述】:

文件是java.nio.channels.SocketChannel.java。 JDK 7u45。摘录如下:

public static SocketChannel open(SocketAddress remote)
    throws IOException
{
    SocketChannel sc = open();
    try {
        sc.connect(remote);
    } catch (Throwable x) {
        try {
            sc.close();
        } catch (Throwable suppressed) {
            x.addSuppressed(suppressed);
        }
        throw x;
    }
    assert sc.isConnected();
    return sc;
}

编译器如何让该代码通过?签名声明了 IOException,但方法的主体捕获了 Throwable 并追溯它。什么不明白?

【问题讨论】:

    标签: java exception java-7 checked-exceptions


    【解决方案1】:

    你不明白的是编译器只检查检查异常,即那些从Exception派生的异常,不包括那些从RuntimeException派生的异常。从 Throwable 开始的层次结构中其他地方的异常不受编译规则的约束。

    【讨论】:

    • 谢谢,@EJP!我觉得你不太对。看这段代码: class ThrowableIsCheckedTest { public static void main(String... args) throws IOException { throw new Throwable(); } } 编译器报错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多