【Java面试题】try-catch-finally结合return执行顺序

对于异常捕获及返回执行顺序的实验和总结

  • try{code1;return1} catch{code2;return2} finally {code3}

    public static void main(String[] args) {
            int flag=testtrycatch();
            System.out.println("flag:"+flag);
        }
        static int testtrycatch(){
                try {
                    int value =1/1;
                    return  111111;
                }catch (Exception e) {
                    System.out.println("catch"+e);
                    return  222222;
                }finally {
                    System.out.println("finally");
                }
        }
    

    无异常的返回,程序执行顺序是code1—code3—return1;

    输出:flag=111111

    有异常的返回,程序执行顺序是code2—code3—return2;

    输出:flag=222222

  • try{code1;return1} catch{code2} finally {code3}returnx

    public static void main(String[] args) {
            int flag=testtrycatch();
            System.out.println(flag);
        }
        static int testtrycatch(){
                try {
                    int value =1/0;
                    return  111111;
                }catch (Exception e) {
                    System.out.println("catch"+e);
                }finally {
                    System.out.println("finally");
                }
            return  333333;
        }
    

    无异常的返回,程序执行顺序是code1—code3—return1;

    输出:flag=111111

    有异常的返回,程序执行顺序是code2—code3—returnx;

    输出:flag=333333

  • try{code1;return1} catch{code2} finally {code3,return3}

    public static void main(String[] args) {
            int flag=testtrycatch();
            System.out.println(flag);
        }
        static int testtrycatch(){
                try {
                    int value =1/1;
                    return  111111;
                }catch (Exception e) {
                    System.out.println("catch"+e);
                }finally {
                    System.out.println("finally");
                    return  666666;
                }
        }
    

    无异常的返回,程序执行顺序是code1—code3—return3;

    输出:flag=666666

    有异常的返回,程序执行顺序是code2—code3—return3;

    输出:flag=666666

发布了195 篇原创文章 · 获赞 335 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/cungudafa/article/details/101201004
今日推荐