问题描述
我寻求帮助以了解为什么会有这种行为差异。
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
块总是被执行——当有异常和没有异常时