1

为什么检查的异常不会在链中传播?

public static void m() {
    FileReader file = new FileReader("C:\\test\\a.txt");
    BufferedReader fileInput = new BufferedReader(file);

}
public static void n() {
    m();
}
public static void o() {
    n();
}

public static void main(String[] args) {
    try {
        o();
    }
    catch(Exception e) {
        System.out.println("caught exception");
    }

}

为什么要处理所有已检查的异常?

4

1 回答 1

1

因为您没有在方法声明中声明它们。已检查的异常必须在可能发生的方法中处理,或者必须声明为由该方法“抛出”。

将您的代码更改为:

public static void m() throws IOException { // <-- Exception declared to be "thrown"
    FileReader file = new FileReader("C:\\test\\a.txt");
    BufferedReader fileInput = new BufferedReader(file);

}
public static void n() throws IOException {
    m();
}
public static void o() throws IOException {
    n();
}

public static void main(String[] args) {
    try {
        o();
    }
    catch(Exception e) {
        System.out.println("caught exception");
    }

}
于 2015-07-05T06:35:47.007 回答