zoukankan      html  css  js  c++  java
  • 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


  • 相关阅读:
    [Kali_Debian] 清除无用的库文件(清理系统,洁癖专用)-布布扣-bubuko.com
    给 Linux 系统“减肥”,系统垃圾清理_系统安装与配置管理_Linux Today
    命令行选项
    SQL 优化
    精通initramfs构建step by step
    常用正则表达式
    Chrome_浏览器开发人员工具
    按键精灵
    CMD命令大全
    50种折纸方法
  • 原文地址:https://www.cnblogs.com/vhviqd/p/11660492.html
Copyright © 2011-2022 走看看