【发布时间】:2015-10-29 11:54:32
【问题描述】:
我有一个非常直观的答案。这个问题与 Java 中的 try-catch-finally 块有关。好吧,就在前几天我在尝试一些东西时遇到了这个编译错误。我也经历了Do you really need the 'finally' block,它回答了我的很多疑问(尤其是评论#2)。
我在这里寻找的是为什么我在注释 #11 到 #13 的行时会看到编译错误(基本上我是在注释内部 catch 块)。当取消注释相同的行时,编译和运行时执行运行良好。如果我能从 OOPS 上下文中得到更多答案,那将增加我的知识并且会有很大的帮助。
提前致谢。 !!
public class TryCatchFinally {
public static void main(String[] args) throws Exception {
try {
System.out.println("Try...");
throw new Exception();
} catch (Exception e) {
System.out.println("Catch...");
try {
System.out.println("Inner Try");
throw new Exception();
} /*catch(Exception e1) {//Line #11
System.out.println("Inner catch");
}*///Line #13
finally{
System.out.println("Inner finally");
}
System.out.println("Going out of catch..");//Line #17
}
finally{
System.out.println("Finally");
}
System.out.println("Going out of try..");//Line #22
}}
【问题讨论】:
-
你看到了什么错误?
-
由于您的代码执行
throw new Exception();,而您永远不会捕获,编译器只是告诉您不可能执行这两个语句。 -
无法访问的代码。实际的问题是:当我取消对第 11 行到第 13 行的注释时,我可以成功执行,但是当我注释这些行(即内部 catch 块)时,为什么它会失败.. ??!!!!
-
因为你在第 10 行抛出异常 throw new Exception();其余代码变得无法访问,并且编译器显示相同的错误
-
因为你抛出了一个你没有处理的异常,这意味着它最终仍会运行,但随后会将异常传播给调用方法
标签: java