try, catch, finally test

        finally is executed in any case:

       ① When there is a return statement in try, the test is as follows:

package study.base_study;

/**
 * Created by Taoyongpan on 2017/11/26.
 * Test the execution order of try catch finally
 */
public class TryTest {

    public static int test1(){
        try {
            return 1;
        }catch (Exception e){
            e.printStackTrace ();
        }finally {
            System.out.println("finally方法");
        }
        return 0;
    }

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

 The test results are as follows:

 

finally method

1

 

Process finished with exit code 0

 

②When an error is thrown and an exception is thrown, the test is as follows:

package study.base_study;

/**
 * Created by Taoyongpan on 2017/11/26.
 * Test the execution order of try catch finally
 */
public class TryTest {

    public static int test1(){
        try {
            return 1/0;
        }catch (Exception e){
            e.printStackTrace ();
        }finally {
            System.out.println("finally方法");
        }
        return 0;
    }

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

 The test results are as follows:

finally method

java.lang.ArithmeticException: / by zero

0

at study.base_study.TryTest.test1(TryTest.java:11)

at study.base_study.TryTest.main(TryTest.java:21)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.lang.reflect.Method.invoke(Method.java:498)

at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

 

Process finished with exit code 0

 

③ When there is also a return statement in the finally method, the return in try will no longer be executed. The test is as follows:

package study.base_study;

/**
 * Created by Taoyongpan on 2017/11/26.
 * Test the execution order of try catch finally
 */
public class TryTest {

    public static int test1(){
        try {
            return 1;
        }catch (Exception e){
            e.printStackTrace ();
        }finally {
            System.out.println("finally方法");
            return 0;
        }

    }

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

 The test results are as follows:

finally method

0

 

Process finished with exit code 0

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326517869&siteId=291194637