为什么扩展 Java Exception 基类的 Exception 类不会被捕获?

问题描述 投票:0回答:1

给出以下程序:

public class App {
    public static void main(String[] args) throws Exception {
        int x = 0;
        try {
            throw new Exception2();
        }
        catch (Exception e) {x += 1;}
        catch (Exception1 e) {x += 2;}
        catch (Exception2 e) {x += 3;}
    }
}


class Exception1 extends Exception {

}

class Exception2 extends Exception1 {

}

带有 Exception1 和 Exception2 的捕获行均给出无法访问的错误。到底是为什么呢?我正在抛出一个新的 Exception2,因此我希望 Exception2 catch 块能够运行。

java exception extends
1个回答
0
投票

问题只是你捕获异常的顺序。从最具体的异常类开始,以最广泛的异常类结束(即异常)

public class App {
    public static void main(String[] args) throws Exception {
        int x = 0;
        try {
            throw new Exception2();
        }
        catch (Exception1 e) {x += 2;}
        catch (Exception2 e) {x += 3;}
        catch (Exception e) {x += 1;}
    }
}


class Exception1 extends Exception {

}

class Exception2 extends Exception1 {

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