首页 文章

在try或catch块上调用return语句或System.exit

提问于
浏览
7

我在采访中得到了以下问题:

如果在try或catch块上调用return语句或System.exit会发生什么?最后会阻止执行吗?

finally块总是被执行吗?

EDIT: 在java中尝试上面的内容之后:

如果我在try块或catch块中放入return语句,则会执行

  • finally

如果我调用System.exit表单try或catch,则

  • finally 块不会运行 .

我不知道背后的原因 .

3 回答

  • 7

    如果在try或catch块上调用return语句或System.exit会发生什么?最后会阻止执行吗?

    return 的情况下,是的 . 如果你想要血腥细节,它们在JLS section 14.20.2中指定 .

    (请注意,在JLS术语中, return 算作突然终止 . 但这并不重要,因为当您仔细分析规范时,您将看到 finally 被执行以进行正常和突然终止 . )

    System.exit() 的情况下,否 . 对 exit 方法的调用永远不会返回,也不会抛出异常 . 因此,线程的"enclosing" finally 子句永远不会被执行 .

    (在JLS的说法中, exit() 调用不会使用任何CPU时间 . 与JVM关闭相关的所有活动都发生在其他线程上 . )

  • 3

    根据the tutorials from Oracle

    注意:如果在执行try或catch代码时JVM退出,则finally块可能无法执行 . 同样,如果执行try或catch代码的线程被中断或终止,则即使应用程序作为一个整体继续,finally块也可能无法执行 .

    这句话似乎意味着:

    • 如果 System.exit(0) 被调用 finallywill not 执行( since the Java VM exits when that statement is called

    • it will 在调用 return 语句时执行( since the Java VM does not exit when that statement is called ) .

    你可以用我写的一些代码来确认:

    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"仍然输出到终端,但是当在 catch 块中调用 System.exit(0) 时,它不是 .

  • 2

    不,它不会,当try-catch没有正常完成时,最后阻止不会被执行 .

    这是JLS或它和州:

    If execution of the try block completes normally, then the finally block is executed
    

    同样适用于 catch block

    If the catch block completes normally, then the finally block is executed.
    

    因为你正在调用 System.exit 来终止 try block 中的程序,所以try-catch没有正常完成,因此 finally block 不会被执行 .

    对于 return statement ,try-catch确实正常完成,因为你没有阻塞 try block (例如无限循环,休眠线程,终止程序等),因此从方法返回后执行 finally block .

相关问题