这是《Java一体机参考》一书中的一个例子
public class CrazyWithZeros {
public static void main(String[] args) {
try {
int answer = divideTheseNumbers(5, 0);
} catch (Exception e) {
System.out.println("Tried twice, still didn't work!");
}
}
public static int divideTheseNumbers(int a, int b) throws Exception {
int c;
try {
c = a / b;
System.out.println("It worked!");
} catch (Exception e) {
System.out.println("Didn't work the first time.");
c = a / b;
System.out.println("It worked the second time!");
} finally {
System.out.println("Better clean up my mess.");
}
System.out.println("It worked after all.");
return c;
}
}
在finally子句执行之后,ArithmeticException被抛出回调用方法。在这种情况下,语句System.out.println("It worked after all.");
将永远不会被执行。但是return c;
发生了什么?
我想知道返回语句是否仍然会返回除法运算的结果?
==========
我尝试将"System.out.println("Better clean up my mess.");
"替换为"System.out.println(c);
",然后对其进行编译,结果如下:
Didn't work the first time. 0 Tried twice, still didn't work!
我不敢相信变量c
可以计算出来。(不过这是个错误的数字)为什么会发生这种事?
然后我还尝试用"return c;
"替换"System.out.println("Better clean up my mess.");
",并删除了finally块下面的语句,它被重新编译。。。由于finally块是执行的,无论try块是否抛出异常或catch块是否捕获异常,返回c;应执行。但结果是:
第一次没用。
看起来c
无法返回。。。
返回c也不执行。它直接进入主方法中的catch块。
第二次执行容易出错的操作时,您希望得到什么?:)
它将生成一个与您在catch
块中出现的类型相同的异常,但当时它不会被处理——在这个catch
块中没有另一个try-catch
。
finally
总是被执行,而不管异常发生还是正常处理流程进行。在您的情况下,您带着异常来到finally
块,并将其抛出给调用者(main
),在那里它由自己的catch
块处理。
我想知道return语句是否仍然会返回除法的结果?
您想要返回什么?您尚未初始化变量c
,并且该变量没有正确的记录。因此,Java不允许在c
中写入"意外或不可预测的东西"。
- 如果方法执行时没有异常或错误,则返回一些值
finally
块对是否执行return语句没有任何影响。(当然,finally
块不应该抛出任何进一步的异常)- CCD_ 20块确定是应该进一步传播该异常还是在该方法内处理该异常
在给定的示例中,从try
块抛出一个ArithmeticException
,它将由相应的catch
块处理。当catch
块再次抛出相同的异常时,给定的return
语句将永远不会执行。
简而言之,return c;
在上述程序中从未被执行,变量c
将作为任何其他局部变量被删除。