-2

考虑以下代码

public void myMethod1() {
    try {
        this.getClass().getMethod("myMethod").invoke(this);
    } catch (Exception e) {
        throw e;
    }
}

public void myMethod1_fixed() throws Exception {
    try {
        this.getClass().getMethod("myMethod").invoke(this);
    } catch (Exception e) {
        throw e;
    }
}

public void myMethod2() {
    try {
        this.getClass().getMethod("myMethod").invoke(this);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    } catch (Exception e) {
        throw e;
    }
}

myMethod1()抱怨没有处理Exception e被抛出的东西,我理解这Exception是因为检查异常并且你被迫处理它,因此myMethod1_fixed()添加throws Exception并且它很高兴。

现在有了myMethod2()它也扔了Exception e,但它虽然没有,但它很高兴throws Exception,意思Exception是不受约束?

4

1 回答 1

2

正如Rethrowing Exceptions with More Inclusive Type Checking中所解释的,当您捕获并重新抛出异常时,编译器会考虑可能发生的实际异常,自 Java 7 起。

所以在

try {
    this.getClass().getMethod("myMethod").invoke(this);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
} catch (Exception e) {
    throw e;
}

您已经在前一个catch子句中捕获了所有已检查的异常,并且只有未检查的异常是可能的。

请注意,您不得修改变量e以使其正常工作。

于 2017-07-17T09:15:42.077 回答