[英]Compilation errors for statement after finally block in Java
我有一个问题,我自己对此有一个非常直观的答案。 这个问题与 Java 中的 try-catch-finally 块有关。 好吧,就在前几天,我正在尝试一些东西,但遇到了这个编译错误。 我也经历过你真的需要“最终”块来回答我的很多疑问(尤其是评论#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
}}
正如其他人所观察到的,您在第 10 行抛出了一个Exception
。之后会发生什么?
当第 11-13 行的内部catch
块被取消注释时,您将在第 10 行抛出Exception
并立即捕获它。 您将打印出“Inner catch”,因为那是catch
块中的内容,然后是“Inner finally”。 异常在您捕获后不再处于活动状态,因此您继续执行第 17 行及以后的操作。
当内部catch
块被移除时,您将在第 10 行抛出Exception
并直接进入第 14 行的finally
块。但该异常尚未被捕获,因此它仍然处于活动状态。 当您退出内部finally
,没有其他catch
块,因此您的方法将立即返回并将异常向上传递到调用链。 (在这种情况下,这不是很远,因为它是main
方法。)重点是第 17 行的println
由于异常而永远无法执行。
Java 编译器足够聪明,可以确定在程序中没有可能的执行路径来执行第 17 行,因此它会给您一个编译错误(以及第 22 行)。
如果您在finally
块之后不需要做任何事情,您就不需要内部捕获。 如果您想让方法保持活动状态并在finally
块之后执行某些操作,则需要保留内部catch
。
内部 try 的最后一行抛出异常,这意味着只会执行 finally 块。
添加另一个 catch 块,或删除该异常抛出,您的问题就解决了。
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
}}
或这个
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
}}
将工作。
在第 10 行,您正在抛出一个需要处理的异常。 由于您没有处理该异常,jvm 无法编译第 10 行之后的代码。 这就是 jvm 给出错误“unreachable code”的原因。 因此,解决方案是通过捕获该异常来处理该异常,或者不要在第 10 行抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.