System.exit()
有什么用? ?如果我不使用它会怎样?我的教授通过以下方式使用它:
public static void main(String[] args) throws Exception {
// make sure that you have the right number of arguments
if (args.length != 1) {
System.out.println("Usage: java FileDemo filename");
System.exit(0);
}
我不知道他为什么要使用它。我也不明白为什么他要求我确保我有正确数量的论点。他怎么知道是否 (args.length !=1)
?我们尚未填充String [] args
在主方法中。
最佳答案
args 的参数由命令行提供(或者如果您使用 IDE,则可以通过 GUI 自行设置命令行参数)。因此,无论您是否在“代码中”没有看到它们,它们都会被设置。
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.
程序中的用法有点无关紧要,因为 main
在执行完成后无论如何都会退出。但是,当用户向程序提供了错误数量的参数时,您的教授可能想演示正确的操作。在这种情况下,您希望释放所有资源并优雅地退出
。在这种情况下,使用 System.exit 就完全没问题了。
关于Java:在 main 方法中使用 System.exit() 和 (String [] args) 的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35674514/