如何解决为什么 RuntimeException 不停止执行 finally 块?
我寻求帮助以了解为什么会有这种行为差异。
public class Test3 {
public static void main(String[] args) {
Double d = new Test3().findPrice$withoutFinally();
//Double d = new Test3().findPrice$withFinally();
System.out.println(d);
}
private double findPrice$withoutFinally() {
double price = -1.0;
int attempt = 0;
do {
try {
price = getPrice();
}
catch (MyException e) {
System.out.println("Caught MyException!");
}
attempt++;
} while (attempt < 3);
return price;
}
private double findPrice$withFinally() {
double price = -1.0;
int attempt = 0;
do {
boolean retry = false;
try {
price = getPrice();
}
catch (MyException e) {
System.out.println("Caught MyException!");
}
finally {
System.out.println("finally");
if (retry) {
System.out.println("retrying...");
attempt++;
} else {
break;
}
}
} while (attempt < 3);
return price;
}
private Double getPrice() throws MyException {
if (true) {
throw new RuntimeException("Testing RE");
}
return null;
}
}
我的意思是,运行我得到的 findPrice$withoutFinally() 方法:
线程“main”中的异常java.lang.RuntimeException:测试RE
这是我期望的行为。但是运行 findPrice$withFinally() 方法我得到了这种意想不到的(对我来说!)行为:
终于 -1.0
findPrice$withFinally() 不应该像 findPrice$withoutFinally() 那样,然后因为异常而停止执行?
谢谢!
解决方法
finally
块总是被执行——当有异常和没有异常时
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。