【发布时间】:2016-08-24 09:48:49
【问题描述】:
我对 Java 还很陌生,无法理解 try-catch-finally 块中的控制流程。每当在 catch 块中捕获到异常时,catch 块之后的代码也会被执行,无论我是否将它放在 finally 块中。那么finally块有什么用呢?
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
如果我将最后一个打印语句放在 finally 块中,没有区别。
【问题讨论】:
-
在
try中抛出一个new RuntimeException(),你会注意到catch 块之后的代码没有被执行。然后添加一个 finally 块。 -
您使用
finally块将您的程序设置为在发生任何异常后可以使用的状态。 -
finally 块中的代码总是 执行,即使在
try或catch中存在return或未处理的异常。这是here 的解释,它是通过非常简单的谷歌搜索找到的。 请使用谷歌。
标签: java exception-handling try-catch-finally