【问题标题】:checked exceptions are not propagated in the chain已检查的异常不会在链中传播
【发布时间】:2015-07-05 06:27:13
【问题描述】:
为什么检查的异常不会在链中传播?
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");
}
}
为什么要处理所有已检查的异常?
【问题讨论】:
标签:
java
exception-handling
checked-exceptions
【解决方案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");
}
}