1. 程式人生 > >System.exit(0)和System.exit(1)區別

System.exit(0)和System.exit(1)區別

1.參考文獻

http://hi.baidu.com/accpzhangbo/blog/item/52aeffc683ee6ec238db4965.html

2.解析

檢視java.lang.System的原始碼,我們可以找到System.exit(status)這個方法的說明,程式碼如下:

  /**
     * 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);
    }
註釋中說的很清楚,這個方法是用來結束當前正在執行中的java虛擬機器。如何status是非零引數,那麼表示是非正常退出。
  1. System.exit(0)是將你的整個虛擬機器裡的內容都停掉了 ,而dispose()只是關閉這個視窗,但是並沒有停止整個application exit() 。無論如何,記憶體都釋放了!也就是說連JVM都關閉了,記憶體里根本不可能還有什麼東西
  2. System.exit(0)是正常退出程式,而System.exit(1)或者說非0表示非正常退出程式
  3. System.exit(status)不管status為何值都會退出程式。和return 相比有以下不同點:   return是回到上一層,而System.exit(status)是回到最上層

3.示例

在一個if-else判斷中,如果我們程式是按照我們預想的執行,到最後我們需要停止程式,那麼我們使用System.exit(0),而System.exit(1)一般放在catch塊中,當捕獲到異常,需要停止程式,我們使用System.exit(1)。這個status=1是用來表示這個程式是非正常退出。