为什么检查异常不会在链中传播?
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");
}
}
为什么应该处理所有已检查的异常?
答案 0 :(得分: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");
}
}