图解try catch 中有return,finally执行吗?什么时候执行?

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">欢迎转载、转载请注明出处 <a target=_blank href="http://http://blog.csdn.net/aizanhao">http://blog.csdn.net/aizanhao</a></span>


1、没有异常时,执行顺序:1-->2-->5-->3;

      执行完1之后,会执行return后面的表达式2(也就是返回值,此时返回值会赋给另一个局部变量(假设为backValue)存放在内存中),之后执行finally中的5,最后执行3(return backValue 而不是 return x)。finally中的代码改变了x的值,但是不会改变返回值。

<span style="font-size:18px;">public class Demo {
   public static void main(String args[]) {
      System.out.println("返回值 x:" + new Demo().test());
	}
	
      public int test(){
	int x = 1;
	try{
	  return x;
	} finally{
	    ++x;
	    System.out.println("finally executed: x=" + x);
	}
      }

}</span>
结果:finally executed: x=2
           返回值 x:1

finally在return之前执行,finally改变了x的值,但是没有改变返回值,返回值在finally执行之前已经保存在内存中。

     2、有异常时,执行顺序:1-->4-->6-->5-->7;

<span style="font-size:18px;">public class Demo {
	public static void main(String args[]) {
		System.out. println ("返回值x:" + new Demo().test());
	}
	
	public int test() {
	  int x = 1;
	  int y;
	  try {
		  y = 1/0;
		  return x;
	    } catch (Exception e) {
	    	return ++x;
	    } finally {
	        ++x;
	        System.out.println("finally executed: x=" + x);
	        }
	}

}</span>
结果:finally executed: x=3
           返回值x:2

            y=1/0有异常,直接跳到catch中,和情况1类似,先计算返回值(++x=2)存放在内存中,然后再执行finally(只改变x的值,不改变返回值,因为返回值已经存放在内存中),最后执行return,将内存中的返回值返回。


    3、finally 中有 return

<span style="font-size:18px;">public class Demo {
	public static void main(String args[]) {
		System.out. println ("返回值x:" + new Demo().test());
	}
	
	public int test() {
	  int x = 1;
	  int y;
	  try {
		  y = 1/0;
		  return x;
	    } catch (Exception e) {
	    	return ++x;
	    } finally {
	        ++x;
	        System.out.println("finally executed: x=" + x);
	        return 8000;
	        }
	}

}
</span>
结果:

        finally executed: x=3
        返回值x:8000
结论:

       1、不管有没有异常,try和catch中有没有return,finally都会执行。

       2、finally不会影响返回值,返回值在进入finally之前已经确定,存放在内存中。

       3、finally是在return表达式之后执行(此时,返回值=(表达式的值)已经存放在内存中),执行完finally之后,最后:return返回值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值