有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java调用返回语句或系统。在“尝试或抓住”挡块上退出

我在采访中被问到以下问题:

What will happen if one calls a return statement or System.exit on try or catch block ? Will finally block execute?

finally块总是被执行吗

编辑: 在java中尝试上述操作后:

  1. 如果我在try块或catch块中放入return语句,但是

  2. finally如果我调用系统,块不会运行。退出尝试或抓住

但我不明白背后的原因


共 (1) 个答案

  1. # 1 楼答案

    根据the tutorials from Oracle

    Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

    这句话似乎暗示:

    • 如果调用System.exit(0),则finally将不会执行(,因为调用该语句时Java VM会退出)
    • 调用return语句时,它将执行(,因为调用该语句时Java VM不会退出)

    你可以用我快速编写的一些代码来确认这一点:

    public class TryExample {
        public static void main(String[] args)
        {
            try {
                int[] i = {1, 2, 3};
                int x = i[3];//Change to 2 to see "return" result
                return;
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("caught");
                System.exit(0);
            } finally {
                System.out.println("finally");
            }
        }
    }
    

    这里,当在try块中调用return时,“finally”仍然输出到terminal,但当在catch块中调用System.exit(0)时,它不是