System.exit(0) 之后还需要 break 吗?

Is break still necessary after System.exit(0)?

在我正在构建的游戏中,用户会看到一些选项,他们可以通过按数字从中进行选择。然后 switch 语句运行相关方法。其中一种选择是退出游戏,我通过 运行 System.exit(0) 来完成。我想知道,退出后的 break 是否仍然有用,如果有用,为什么?如果 exit 是 switch 语句中的最后一个选项,是否有区别?

代码如下:

switch(choice) {
    case 1: getEntityOverview();
        break;
    case 2: worldMap.PrintMap();
        break;
    case 3: moveAllOnInput();
        break;
    case 4:
        System.out.println("You are exiting the game, "
            + "thanks for playing!");
        System.exit(0);
        break;
}

A break 阻止了 'fall through' 到下一个 case 项目。此处不需要 break,原因有二:

  • 有问题的选项是 switch 语句中的最后一项,因此没有什么可以落到
  • 即使下面有另一个项目,它也永远不会 'fall through',因为 System.exit() 不会 return 因为它会终止应用程序(+/- 各种挂钩)

也许这个问题的意思是 'does System.exit() ever return?'(在这种情况下,如果它不是 switch 语句中的最后一项,break可能需要)。

根据 documentation:

[System.exit()] Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.

The call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n)

我不太喜欢那样 'normally'。 Runtime.exit 有相同的 'normally'。然而,我怀疑这是对他们可以抛出异常这一事实的引用,在这种情况下,缺少 break 不是问题。 Jon Skeet 似乎并不关心它 here

就是说,没有什么可以阻止 你把 break 语句放在那里。事实上,这可能是一个很好的计划,以防有人在之后添加另一个项目,然后其他人将 System.exit() 换成可能 return 的东西,例如调用 'Are you sure you want to quit'?

不,您不需要此 break 声明。

来自 class System 的 javadoc :

public static void exit(int status) Terminates the currently running Java Virtual Machine.

这将结束您的应用程序的执行,您的程序将退出,并且不会执行进一步的指令,除非您注册了 Shutdown Hook

即使是 finally 块也不会被执行。

因此,您放置 System.exitcase 位置没有任何区别。