Java - 更精确的重新抛出的功能

Java - More Precise Rethrown Feature

在 oracle 官方网站上写:(http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html#rethrow)

In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

  • The try block is able to throw it.

  • There are no other preceding catch blocks that can handle it.

  • It is a subtype or supertype of one of the catch clause's exception parameters.

请注意第三点(它是catch子句异常参数之一的子类型或超类型。)

这到底意味着什么?你能给我举个例子吗?看不懂。

子类型部分非常简单 - 因为所有子类型 也是它们的父类型,所以允许捕获和重新抛出任何子类型是微不足道的。我相信从第一天起就是这种情况(或者至少比我能记得的更早。)

至于超类型,那是在Java7中添加的增强功能,举个例子:

public class Demo {

    static class Exception1 extends Exception{}

    public static void main(String[] args) throws Exception1 {
        try {
            throw new Exception1();
        }
        catch(Exception ex) {
            throw ex;
        }
    }

}

您最初可能希望这不会编译,因为 main() 方法仅声明它抛出 Exception1 类型,但 catch 参数指定 Exception。显然并非所有 Exception 对象都是 Exception1.

然而,catch参数是Exception1的超类型(满足上面excert的超类型要求),抛出的异常类型与声明的类型相同throws 关于方法的声明。因此,编译器可以验证在此上下文中重新抛出此异常是否有效,并且编译成功。