由一道笔试题讨论Java中try、catch、finally的执行顺序

由一道笔试题讨论Java中try、catch、finally的执行顺序

try、catch、finally在Java中的执行顺序由try中的语句是否发生异常决定。

请看这一段代码

class test1 {

    private static int testFinallyFunc() {
        String s = "123";
        int result;
        try {
            s.equals("ss");
            result = 1;
            System.out.println("try " + result);
        } catch (Exception e) {
            result = 2;
            System.out.println("catch " + result);
            return result;
        } finally {
            result = 3;
            System.out.println("finally " + result);
            return result;
        }
   
    }

    public static void main(String[] a) throws Exception {
        int returnResult = testFinallyFunc();
        System.out.println("get return result " + returnResult);
    }
}

代码的运行结果是

try 1
finally 3
get return result 3

我们来探究一下,try中的语句没有发生异常,所以try中的语句都会执行,然后就跳过catch中的语句,但是finally会执行。finally后面的return语句也会执行。

 

接下来看另一种情况

 

class test1 {

    private static int testFinallyFunc() {
        String s = null;
        int result;
        try {
            s.equals("ss");
            result = 1;
            System.out.println("try " + result);
        } catch (Exception e) {
            result = 2;
            System.out.println("catch " + result);
            return result;
        } finally {
            result = 3;
            System.out.println("finally " + result);
            return result;
        }
        
    }

    public static void main(String[] a) throws Exception {
        int returnResult = testFinallyFunc();
        System.out.println("get return result " + returnResult);
    }
}

代码的运行结果是

catch 2
finally 3
get return result 3

原因如下,s为null,s在调用equals方法时发生异常,然后try里面的result=1和打印输出语句不会执行,catch和finally里面的语句会执行。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注