• try ,catch ,finally执行流程


    1、如果catch 里面有return,finally里面的代码还会执行吗?

      答案:会,在return之前执行。

    例1:finally里面没有return

      public class TestTryCatch {

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

    public static int getInt() {
    int a = 10;
    try {
    System.out.println(a / 0);
    a = 20;
    } catch (ArithmeticException e) {
    a = 30;
    a = catchException(a);
    return a+10; //当执行到这里的时候 return 55 已经准备好了,但是此时 他会去看有没有finally,如果有,先去执行finally里面的代码,
    //如果finally里面有那个return,就直接返回了,try里面的55就不会返回了。如果finally里面没有return,那么执行完其他代码之后,会继续执行return 55;所以返回结果就是55
    } finally {
    a = 40;
    }
    return a;
    }

    private static int catchException(int a){
    return a+15;
    }

    结果: 55

    例2. finally里面有return
    public class TestTryCatch {
    public static void main(String[] args) {
    System.out.println(getInt());
    }

    public static int getInt() {
    int a = 10;
    try {
    System.out.println(a / 0);
    a = 20;
    } catch (ArithmeticException e) {
    a = 30;
    a = catchException(a);
    return a+10; //当执行到这里的时候,他回去看有没有finally,如果有,先去执行finally里面的代码,
    //如果finally里面有那个return,就直接返回了,a+10就不会执行了。如果没有,那么继续执行之前的
    //a+10,此时的a+10中的a=30+15,而不是finally里面的数字。
    } finally {
    a = 40;
    return a; //这里直接返回40,所以上面的try里面的return 55就不会在执行,所以返回结果就是40
    }
    // return a;
    }
    private static int catchException(int a){
    return a+15;
    }
    }

    3.catch与finally里面都没有return
    public class TestTryCatch {
    public static void main(String[] args) {
    System.out.println(getInt());
    }

    public static int getInt() {
    int a = 10;
    try {
    System.out.println(a / 0);
    a = 20;
    } catch (ArithmeticException e) {
    a = 30;
    } finally {
    a = 40;
    }
    return a;
    }
    }

    结果:40,按顺序执行,最后返回40


  • 相关阅读:
    编辑文章
    POJ_1195 Mobile phones 【二维树状数组】
    WCF探索之旅(三)——IIS公布WCF服务
    doT.js具体使用介绍
    数据结构:最小生成树--Kruskal算法
    关于打开sdk下载不了的最优秀解决方式
    JS 之 数据类型转换
    MongoDB学习笔记<六>
    Spring、Hibernate 数据不能插入到数据库问题解决
    Cocos2d-x 3.0final 终结者系列教程16-《微信飞机大战》实现
  • 原文地址:https://www.cnblogs.com/vhviqd/p/11660492.html
Copyright © 2020-2023  润新知