Java中Try和Finally初步解析.

在java中,我们一般都知道处理异常时需要用到try-catch-finally.但是具体的执行过程,笔者一直没弄明白. 所以笔者做了以下实验来确定代码的执行顺序:


CODE 1:

public class TryCatchTest {

    public static void method1() {
        try{
            System.out.println("method1 try block");
            throw new Exception("method Exception");
        }catch(Exception e){
            System.out.println("method1 catch block");
        }finally{
            System.out.println("method1 finally block");
        }
    }
    public static void main(String[] args) {
        try {
            System.out.println("try block");
            method1();
            throw new Exception("my Exception");
        } catch (Exception e) {
            System.out.println("catch block");
        }finally{
            System.out.println("finally block");
        }
    }

}
执行结果:

try block
method1 try block
method1 catch block
method1 finally block
catch block
finally block

由此可见,try-catch-finally的执行顺序是:当try中有异常时执行catch块代码,最后执行finally块代码. 若try块中未发现异常,则不执行catch块中的代码.


CODE 2:

public class TryCatchFinallyTest {

	public static int method1(int i) {
		try{
			System.out.println("method1 try block 2"+(++i));
			return method2(i);
		}finally{
			System.out.println("method1 finally block 3"+(++i));
		}
	}
	public static int method2(int i) {
		try{
			System.out.println("method2 try block 3"+(++i));
			return i;
		}finally{
			System.out.println("method2 finally block 4"+(++i));
		}
	}
	public static void main(String[] args) {
		int i=0;
		try {
			System.out.println("try block before 1"+(++i));
			System.out.println(method1(i));
			
			
		} finally{
			System.out.println("finally block 2"+(++i));
		}
	}

}
执行结果:

try block before 11
method1 try block 22
method2 try block 33
method2 finally block 44
method1 finally block 33
3
finally block 22


分析: 当程序执行try块中的return之后,return的结果会被暂时存储在临时数据区域内, 然后程序继续执行finally块代码, 最后,将数据区中的数据返回给上层函数. 特别注意,如果finally块中也有return,则finally块中的返回值会被存入数据区并覆盖try块中的返回值. 概括地说, finally执行的时间是在return语句执行之后, 方法返回之前(即上层方法获取到该方法的返回值之前)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值