异常之finally执行

三点总结:

1.finally块的语句在try或catch中的return语句执行之后返回之前执行。

2.finally里的修改语句可能影响也可能不影响try或catch中 return已经确定的返回值

3.若finally里也有return语句则覆盖try或catch中的return语句直接返回。

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Test2 {
	public static void main(String[] args) {
		Test2 m = new Test2();
		System.out.println(m.amethod1());//1进入amethod1
	}
	public int amethod1() {
		 try {
			 new FileInputStream("Hello.txt");
 		 } catch (FileNotFoundException e) {
				System.out.println("catch block");//2输出catch block
				return amethod2();//3进入amethod2
		}finally{
			System.out.println("finally block");//6输出
		}
		return 0;//上面已经return 不执行
	}
	
	public static int  amethod2() {
		System.out.println("return mathod");//4输出
		return -1;//5执行   7返回输出
	}
}

输出结果:

catch block
return mathod
finally block
-1

例2

public class Test1 {

    public static void main(String[] args) {  
        System.out.println(test1());
    }

    public static int test1() {
        int b = 20;
        try {
            System.out.println("try block");//1输出
            return b += 80; //2执行  5返回输出
        }
        catch (Exception e) {
            System.out.println("catch block");
        }
        finally {
            System.out.println("finally block");//3输出
            if (b > 25) {
                System.out.println("b>25, b = " + b);//4输出
            }
           // return b;
        }
        return b;//不执行
    }
    
}
输出结果:

try block
finally block
b>25, b = 100
100

例3:与例2对比

public class Test1 {

    public static void main(String[] args) {
        System.out.println(test1());
    }

    public static int test1() {
        int b = 20;
        try {
            System.out.println("try block");//1输出
            return b += 80; //2执行 
        }
        catch (Exception e) {
            System.out.println("catch block");
        }
        finally {
            System.out.println("finally block");//3输出
            if (b > 25) {
                System.out.println("b>25, b = " + b);//4输出
            }
           return b+1;//5 执行输出
        }
        //return b;
    }
    
}

输出结果:

try block
finally block
b>25, b = 100
101



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值