Java 中的System.exit

时间:2023-03-08 22:35:29
Java 中的System.exit

在java 中退出程序,经常会使用System.exit(1) 或 System.exit(0)。

查看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.
* <p>
* This method calls the <code>exit</code> method in class
* <code>Runtime</code>. This method never returns normally.
* <p>
* The call <code>System.exit(n)</code> is effectively equivalent to
* the call:
* <blockquote><pre>
* Runtime.getRuntime().exit(n)
* </pre></blockquote>
*
* @param status exit status.
* @throws SecurityException
* if a security manager exists and its <code>checkExit</code>
* method doesn't allow exit with the specified status.
* @see java.lang.Runtime#exit(int)
*/
public static void exit(int status) {
Runtime.getRuntime().exit(status);
}

当 status为0 时正常退出程序, 当status为非0数字时异常退出。 终止当前的Java虚拟机。

System.exit()方法返回程序的最顶层, return和它相比是返回上一层。

当程序执行到System.exit()方法后就会停止运行。 如果希望程序遇到System.exit后只退出当前用例,不退出当前程序,可以考虑在异常中做手脚。

Java 中的System.exit