try catch 执行顺序详解

代码详情

public class tryTest {

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

    private static String getString(){
        try {
            System.out.println("主体");
            throw new Exception();
        }catch (Exception e ){
            System.out.println("catch");
            return returnCatch();
        }finally {
            System.out.println("finally");
            return returnFinally();
        }
    }

    private static String returnCatch(){
        System.out.println("returnCatch");
        return "returnCatch";
    }

    private static String returnFinally(){
        System.out.println("returnFinally");
        return "returnFinally";
    }

}

执行详情

主体
catch
returnCatch
finally
returnFinally
returnFinally

故先

1 执行主体
2 执行catch
3 执行catch返回方法
4 执行finally
5 执行finally方法
6 然后把finally值返回去

实测要是没有finally里面的返回 则返回 catch里面的

你可能感兴趣的:(Java)