finally语句块一定执行吗?

答案是不一定。存在很多特殊情况导致finally语句块不执行。如:

  • 直接返回未执行到 finally 语句块
  • 抛出异常未执行到 finally 语句块
  • 系统退出未执行到 finally 语句块

等...

代码如下

public static String test() {
    String str = null;
    int i = 0;
    if (i == 0) {
        return str;//直接返回未执行到finally语句块
    }
    try {
        System.out.println("try...");
        return str;
    } finally {
        System.out.println("finally...");
    }
}
 
public static String test2() {
    String str = null;
    int i = 0;
    i = i / 0;//抛出异常未执行到finally语句块
    try {
        System.out.println("try...");
        return str;
    } finally {
        System.out.println("finally...");
    }
}
 
public static String test3() {
    String str = null;
    try {
        System.out.println("try...");
        System.exit(0);//系统退出未执行到finally语句块
        return str;
    } finally {
        System.out.println("finally...");
    }
}

 

  

来一道刷了进BAT的面试题?

posted @ 2019-11-05 19:41  ConstXiong  阅读(647)  评论(0编辑  收藏  举报