Java中的finally

来源:互联网 发布:discuz数据库备份目录 编辑:程序博客网 时间:2024/04/29 22:26

1. 在try中return后,finally是否会执行?

2. 在try中throw exception后,finally是否会执行?

3. 在try中System.exit(0)后,finally是否会执行?

例子:

public class Test2 {public static void main(String[] args) throws Exception {returnValue();tryException();exit();}public static int returnValue() {try{return 0;} finally {System.out.println("finally in returnValue");}}public static void tryException() throws Exception {try{throw new Exception("My exception");} finally {System.out.println("finally in tryException");}}public static void exit() {try{System.exit(0);} finally {System.out.println("finally in exit");}}}
以下是屏幕输出:

finally in returnValue
finally in tryException
Exception in thread "main" java.lang.Exception: My exception
    at other.Test2.tryException(Test2.java:21)
    at other.Test2.main(Test2.java:7)