Execution order of finally and return in Java

1. Try and catch contain return

public class tryDemo {
    public static int show() {
        try {
            return 1;
        } finally {
            System.out.println("执行finally模块");
        }
    }

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

Execute finally module 1

public class tryDemo {
    public static int show() {
        try {
            int a = 8 / 0;
            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            System.out.println("执行finally模块");
        }
    }

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

Execute finally module 2

2. Finally with return

public class tryDemo {
    public static int show() {
        try {
            int a = 8 / 0;
            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            System.out.println("执行finally模块");
            return 0;
        }
    }

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

Execute finally module 0

3. Change the return value in finally

public class tryDemo {
    public static int show() {
        int result = 0;
        try {
            return result;
        } finally {
            System.out.println("执行finally模块");
            result = 1;
        }
    }

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

Execute finally module 0

public class tryDemo {
    public static Object show() {
        Object obj = new Object();
        try {
            return obj;
        } finally {
            System.out.println("执行finally模块");
            obj = null;
        }
    }

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

Execute the finally module Java lang. Object@15db9742

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>