【发布时间】:2018-07-12 01:58:13
【问题描述】:
我有这样的代码:
class ExceptionTest{
public Integer divide(int a, int b) {
try {
return a/b;
}finally {
System.out.println("Finally");
}
}
}
public class Three {
public static void main(String[] args) {
ExceptionTest test = new ExceptionTest();
try {
System.out.println(test.divide(10, 0));
}catch(Exception e) {
System.out.println("DIVIDED BY 0!");
}
}
}
当我运行它打印的代码时:
Finally
DIVIDED BY 0!
这是为什么呢?如果捕获到异常,则不应仅“除以 0!”打印出来?
编辑:
我知道 finally 总是被打印出来的,但我的意思是在 main 的 try-catch 块中调用了名为“divide”的方法中的 try-finally。因此,如果捕获到异常,为什么会打印 try-catch 中的某些内容?即使我的 ExceptionTest 类看起来像这样:
class ExceptionTest{
public Integer divide(int a, int b) {
System.out.println("Finally")
return a/b;
}
}
所以没有try-finally块并且抛出异常,我仍然有
Finally
Divided by 0!
【问题讨论】:
-
finally块的全部意义在于绝对保证其中的代码可以运行。 -
最终将被执行。这就是拥有该块类型的全部意义。
-
你能解释一下为什么你认为
finally不应该被执行吗? -
@BoristheSpider 我已将我的问题编辑得更具体,我认为这不是您标记的重复问题。
-
@Gregory 您的编辑没有多大意义,因为在进行除法之前您有
System.out.println("Finally")。所以显然打印将在抛出异常之前执行。异常发生在a/b,此时您的方法因异常而停止。
标签: java exception try-catch try-catch-finally finally