Java 中的System.exit

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

查看System.exit()方法的源码,如下

 1   /**
 2      * Terminates the currently running Java Virtual Machine. The
 3      * argument serves as a status code; by convention, a nonzero status
 4      * code indicates abnormal termination.
 5      * <p>
 6      * This method calls the <code>exit</code> method in class
 7      * <code>Runtime</code>. This method never returns normally.
 8      * <p>
 9      * The call <code>System.exit(n)</code> is effectively equivalent to
10      * the call:
11      * <blockquote><pre>
12      * Runtime.getRuntime().exit(n)
13      * </pre></blockquote>
14      *
15      * @param      status   exit status.
16      * @throws  SecurityException
17      *        if a security manager exists and its <code>checkExit</code>
18      *        method doesn't allow exit with the specified status.
19      * @see        java.lang.Runtime#exit(int)
20      */
21     public static void exit(int status) {
22     Runtime.getRuntime().exit(status);
23     }

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

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

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

原文地址:https://www.cnblogs.com/Theladyflower/p/4018417.html