java中【 return和finally 】问题!【借鉴与改编】

public class TestException {
	public static void main(String[] args) {
		System.out.print(tt());
	}

	public static int tt() {
		int b = 23;
		try {
			System.out.println("yes");
			return b += 88;
		} catch (Exception e) {
			System.out.println("error      :      " + e);
		} finally {
			if (b > 25) {
				System.out.println("b>25      :      " + b);
			}
			System.out.println("finally");
		}
		return b;
	}
}


运行结果:

yes
b>25      :      111
finally
111

也就是说明finally语句在return语句执行完了以后才执行的.

OK,那么问题来了,如果我把finally语句改成这样呢:

public class TestException {
	public static void main(String[] args) {
		System.out.print(tt());
	}

	@SuppressWarnings("finally")
	public static int tt() {
		int b = 23;
		try {
			System.out.println("yes");
			return b += 88;
		} catch (Exception e) {
			System.out.println("error      :      " + e);
		} finally {
			if (b > 25) {
				System.out.println("b>25      :      " + b);
			}
			System.out.println("finally");
			return 100;
		}
	}
}

yes
b>25      :      111
finally
100

这样又说明了一个问题,finally语句块里面的return把原来的return给覆盖了!!变成了新的返回值了.


倘若改成这样:

public class TestException {
	public static void main(String[] args) {
		System.out.print(tt());
	}

	@SuppressWarnings("finally")
	public static int tt() {
		int b = 23;
		try {
			System.out.println("yes");
			return b;
		} catch (Exception e) {
			System.out.println("error      :      " + e);
		} finally {
			if (b > 25) {
				System.out.println("b>25      :      " + b);
			}
			System.out.println("finally");
			b=  100;
		}
		return b;
	}
}

打印结果:

yes
finally
23

说明了一个问题,如果finally语句中没有返回语句覆盖的话,那么原来的返回值就不会变,不管你是不是改变了要返回的那个变量.


       最后总结:

    碰到try语句中的return,那么先把return的值放在某个池中(怎么我也说起池来了,明明根本还不懂的)?       
  然后执行finally里面的代码块,如果有返回值覆盖语句,就改变先前放在池中的那个值,  如果没有,  就把那个池中的东西取出来返回出去.


public class FourTest{

	/**
	 * @param args
	 */
	public static int getInt (String message) {
		int x = 0;
		try{
			return x = Integer.parseInt(message);
		}catch(NumberFormatException e){
		}finally{
			x = 100;
		}
		return x;
	}
	
	public static void main(String[] args){
		System.out.println(FourTest.getInt("1001"));
		// 若是  1001 则打印 1001
		// 若是   1001s  则打印  100
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值