异常类已声明但未抛出

问题描述 投票:-2回答:1

这里test没有抛出Exception对象,但我已经处理过了。由于Exception是一个经过检查的异常,因此它不会在catch块中抛出无法访问代码的编译器错误

class Ece extends Exception {}
public class Excep {
    public static void test()  { }
    public static void main(String[] args) {
        try {
            test();
        } catch (Exception E) {

        }
    }
}
java exception exception-handling unreachable-code defensive-programming
1个回答
1
投票

ExceptionRuntimeException作为子类。 RuntimeException及其子类不需要在methd签名中声明。

在这种情况下,您将捕获所有可能的Exception子类,包括所有不需要签名声明的子类。如果您的test方法抛出例如ArrayIndexOutOfBoundsException,您将能够捕获并处理它,但test签名将不会受到影响。

进一步阅读here

© www.soinside.com 2019 - 2024. All rights reserved.