繁体   English   中英

已检查的异常不在链中传播

[英]checked exceptions are not propagated in the chain

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

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");
    }

}

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

因为您尚未在方法声明中声明它们。 被检查的异常必须在可能发生它们的方法中进行处理,或者必须被该方法声明为“抛出”。

将您的代码更改为:

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");
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM