try catch finally

1.如果没有异常,先执行try代码块,再执行finally代码块;

       try{
            System.out.println(111);
        }catch(Exception e){
            System.out.println(222);
        }finally{
            System.out.println(333);
        }

结果:111  333

2.如果有异常,先执行try代码块,再执行catch代码块,最后执行finally代码块;

        int i = 1;
        try{
            System.out.println(111);
            int a = i/0;
        }catch(Exception e){
            System.out.println(222);
        }finally{
            System.out.println(333);
        }

结果:111   222   333

3.如果在try代码块加入return,finally代码块在return前执行;

        try{
            System.out.println(111);
            return;
        }catch(Exception e){
            System.out.println(222);
        }finally{
            System.out.println(333);
        }

结果:111  333

4.如果在try代码块加入return且有异常,

public class Test15 {
    public static int test3(){
    try{
        int a = 5/0;
        return 1;
    }catch (ArithmeticException e){
        System.out.println(222);
        return 2;
    }finally {
        System.out.println(333);
    }
}
    public static void main(String[] args) throws MyException {
        System.out.println(test3());
    }

结果:222  333  2

5.try代码块中有return

public static String test1(){
        try{
            System.out.println(111);
            return test2();
        }finally{
            System.out.println(333);
        }
}
    public static String test2() {
        System.out.println(444);
        return "test2 return";
    }
    public static void main(String[] args) throws MyException {
        System.out.println(test1());
}

结果:111  444  333  test2 return

return test2()  等价于

String tmp = test2();

return tmp;

总结:如有异常,按try catch finally 的顺序运行

try 和catch代码块中有return ,则finally代码块在return之前运行,

如果finally代码块中有return,则提前结束进程。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值