JAVA Try Catch Finally 代码执行顺序

    public void test () {
        //1
       throw new RuntimeException();
        //2
    }
基本知识

如果有错误,不进行try-catch则会编译报错。

    public void test () {
        try {
        // 1
            throw new NullPointerException();
        //2
        } catch (RuntimeException r) {
        //3 
        } catch (Exception e) {
        //4
        } finally {
        //5
        }
        //6
    }
基本知识

try-catch中,可以有多个catch,但是catch的错误的类型,从上到下应该是越靠近try的catch的错误类型要越精确,范围越小,不然会编译报错,而且错误只会被, 举个例子:虽然RuntimeException也是Exception,如果你throw出来的是NullPointerException,NullPointerException虽然是Exception,也是RuntimeException,但是如上图代码所示,会优先匹配最靠近这个Exception 的catch,且只会被一个catch匹配,,所以会执行3号区域代码,然后执行5号区域代码,最后执行6号区域代码。

    public void test () {
        try {
        // 1
            throw new NullPointerException();
        //2
        } catch (RuntimeException r) {
        //3 
        } catch (Exception e) {
        //4
        } finally {
        //5
        }
        //6
    }

执行顺序如下:

  1. 执行1号区域代码
  2. 由于throw了RuntimeException 则会直接执行对应的3号区域的代码
  3. 执行5号区域的代码
  4. 执行6好区域的代码
    public int testFinally () {
        int a = 0 ;
        try {
        1
            throwException();
        2   return a;
        } catch (RuntimeException r) {
        3    System.out.println("RuntimeException");
        4   return a;
        } catch (Exception e) {
        5    System.out.println("Exception");
        } finally {
        6   System.out.println("finally");
        7   a=1;
        }
        return 0;
    }

    public void throwException () {
        throw new RuntimeException();
    }

执行顺序如下:

  1. 1号区域代码
  2. 3号区域代码
  3. 4号区域代码,但是此时不会直接返回,而是将a的值复制保存一份
  4. 6号区域代码
  5. 7号区域代码,但是此时已经不会影响a在第3步的值
  6. 4号区域代码,return 结束函数 此时a=0
    public int testFinally () {
        int a = 0 ;
        try {
        1
            throwException();
        2   return a;
        } catch (RuntimeException r) {
        3    System.out.println("RuntimeException");
        4   return a;
        } catch (Exception e) {
        5    System.out.println("Exception");
        } finally {
        6   System.out.println("finally");
        7   a=1;
        8   return a;
        }
        9  System.out.println("Exception");
        10 return a;
    }

    public void throwException () {
        throw new RuntimeException();
    }

执行顺序如下:

  1. 1号区域代码
  2. 3号区域代码
  3. 4号区域代码,但是此时不会直接返回,而是将a的值复制保存一份
  4. 6号区域代码
  5. 7号区域代码,但是此时已经不会影响在第3步的要返回的值
  6. 8号区域代码,此时a=1 此时 return a=1,结束函数
    9,10不会执行。
    这就是为什么一般finally不写return。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值