public class Test {
public static int testInt() {
int x = 0;
try {
x = 1;
System.out.println("x=1");
return x;
}
finally {
x = 2;
System.out.println("x=2");
}
}
public static Ref testRef() {
Ref ref = new Ref();
try {
ref.x = 1;
System.out.println("x=1");
return ref;
}
finally {
ref.x = 2;
System.out.println("x=2");
}
}
public static void main(String[] args) {
System.out.println("x=? " + testInt());
System.out.println("x=? " + testRef());
}
private static class Ref {
private int x;
public String toString(){
return String.valueOf(x);
}
}
}
必须知道,别滥用-finally
最新推荐文章于 2025-08-18 07:36:37 发布
本文通过两个Java示例探讨了try-finally语句中finally块的执行机制及其对方法返回值的影响。首先定义了一个名为Test的公共类,该类包含两个静态方法:testInt()返回整数并打印相关信息,testRef()返回自定义引用类型Ref的实例并同样打印信息。通过main方法调用这两个方法并输出结果,展示了finally块如何改变方法的实际返回值。
917

被折叠的 条评论
为什么被折叠?



