【发布时间】:2013-12-23 20:03:31
【问题描述】:
在下面的示例中,您可以看到使用外部 catch 子句无法捕获 IOException(名为 FOURTH)异常。这是为什么? 我知道如果在嵌套的 try 块中抛出异常,可以使用外部捕获来捕获异常。 如果将 b 静态变量值更改为 false 则可以看到。
但是为什么我们不能使用外部 catch 捕获嵌套 catch 子句中抛出的异常呢?
import java.io.*;
public class Exceptions {
static boolean b = true;
public static void main(String[] args){
try {
exceptions(b);
} catch (Exception e) {
System.out.println(e + " is handled by main().");
}
}
static void exceptions(boolean b) throws Exception{
try{
if(b) throw new FileNotFoundException("FIRST");
try{
throw new IOException("SECOND");
}
catch(FileNotFoundException e){
System.out.println("This will never been printed out.");
}
}
catch(FileNotFoundException e){
System.out.println(e + " is handled by exceptions().");
try{
throw new FileNotFoundException("THIRD");
}
catch(FileNotFoundException fe){
System.out.println(fe + " is handled by exceptions() - nested.");
}
try{
throw new IOException("FOURTH");
}
finally{}
}
catch(Exception e){
System.out.println(e + " is handled by exceptions().");
}
}
}
如果 b = true 的输出:
java.io.FileNotFoundException:FIRST 由 exceptions() 处理。 java.io.FileNotFoundException: THIRD 由 exceptions() 处理 - 嵌套。 java.io.IOException: FOURTH 由 main() 处理。
如果 b = false 的输出:
java.io.IOException: SECOND 由 exceptions() 处理。
【问题讨论】:
-
如果在“FOURTH”异常之后删除
finally{}会发生什么? -
确实如此。找到最后一个
try/catch语句。 -
你不是从
try块中扔掉它,而是从catch块中扔掉它。 -
当你运行这个时会发生什么,异常是否完全未被捕获?
-
@Chthonic Project 如果您最终删除{},那么它将无法编译
标签: java exception nested try-catch