关于Java异常处理try catch finally返回值的问题

通过简单例题快速掌握try catch finally返回值顺序

观察以下代码:

public class Text01 {
	public static void main(String args[]) {
		test();	
	}
	public static void test() {
		int temp=1;
		try {
			System.out.println(temp);					
		}catch(Exception e) {
			System.out.println(temp);
		}finally {
			++temp;
			System.out.println(temp);	
		}
	}
}

运行结果如下:
在这里插入图片描述
以上代码未出现异常,执行完try语句后直接执行finally语句,输出1后变量temp自加为2并输出。

接下来再看一道题:

public class Text02 {
	public static void main(String args[]) {
		System.out.println(test()+"x");	
	}
	public static int test() {
		int temp=1;
		try {
				System.out.println(temp+"y");
				return ++temp;
		}catch(Exception e) {
			System.out.println(temp);
			return ++temp;
		}finally {
			++temp;
			System.out.println(temp+"z")
		}
	}
}

答案如下:
在这里插入图片描述
此题的执行步骤为:
1、调用test()方法
2、执行try块里的内容,输出1y,变量temp的值自加为2并储存在变量域和返回值域中
3、未发现异常,不执行catch块里内容
4、执行finally块中的语句,temp自加为3并保存在变量域中,输出3z
5、test()方法执行完毕,返回保存在返回值域中的内容
6、返回值域中temp的值为2,不受finally块里语句的影响,输出2x

此题加在try和catch里加入了return语句,观察运行结果发现在finally中temp的自加操作并未改变temp的返回值,由此可得结论函数的返回值是在finally块执行前确定的,不论在finally块如何改变返回值,函数返回值都不会发生改变。

但如果在finally里加入返回值,那么返回值就会被改变:

public class Text03 {
	public static void main(String args[]) {
		System.out.println(test());	
	}
	public static int test() {
		int temp=1;
		try {	
				return temp;
		}catch(Exception e) {
			System.out.println(temp);
			return ++temp;
		}finally {
			++temp;
			return temp;
		}
	}
}

运行结果:
在这里插入图片描述
在函数未返回try中的temp值时fianlly就已经返回,函数相当于更新返回值域里temp的值并提前结束,所以在temp自加为2后直接返回,输出2。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值