【发布时间】:2018-03-21 09:54:58
【问题描述】:
这是《Java All-in-one Desk Reference》一书中的一个例子
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; 发生了什么?
不知道return语句是否还会返回除法的结果?
========
我尝试将“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 可以计算出来。 (虽然是错误的数字)为什么会发生这种情况?
然后我也尝试将“System.out.println("Better clean up my mess.");”替换为“return c;”并删除了finally块下面的语句,它再次编译......由于finally块被执行,无论是否抛出任何异常try 块或被任何 catch 块捕获,返回 c;应该被执行。但结果如下:
第一次没用。
看起来c 无法返回...
【问题讨论】:
-
试试 System.out.println(c); , 进行调试。
-
计算机是可预测的机器。但实际上,它们只是功能强大的计算器。如果您在袖珍计算器上尝试相同的除法会发生什么?同一件事情。否则计算器将一文不值,你不能相信它们。因此,如果某些事情不起作用,不要只是再试一次,要尝试了解分裂失败的原因。可能你除以零......另外,捕捉“异常”而不是“AMoreSpecificException”是犯罪,不应该这样做。
标签: java