必须知道,别滥用-finally

本文通过两个Java示例探讨了try-finally语句中finally块的执行机制及其对方法返回值的影响。首先定义了一个名为Test的公共类,该类包含两个静态方法:testInt()返回整数并打印相关信息,testRef()返回自定义引用类型Ref的实例并同样打印信息。通过main方法调用这两个方法并输出结果,展示了finally块如何改变方法的实际返回值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值