查看java.lang.System的源碼。我們能夠看到System.exit()這種方法等價於Runtime.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);
}
從方法的凝視中能夠看出此方法是結束當前正在執行的Java虛擬機,這個status表示退出的狀態碼,非零表示異常終止。注意:無論status為何值程序都會退出,和return 相比有不同的是:return是回到上一層,而System.exit(status)是回到最上層。
System.exit(0):不是非經常見,做過swing開發的可能用過這方法,一般用於Swing窗口關閉button。(重寫windowClosing方法時調用System.exit(0)來終止程序,Window類的dispose()方法僅僅是關閉窗口。並不會讓程序退出)。
System.exit(1):很少見,一般在Catch塊中會使用(比如使用Apache的FTPClient類時,源代碼中推薦使用System.exit(1)告知連接失敗),當程序會被腳本調用、父進程調用發生異常時須要通過System.exit(1)來告知操作失敗,默認程序終於返回的值返是0,即然發生異常默認還是返回0,因此在這樣的情況下須要手工指定返回非零。
