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

查看java.lang.System的源代碼,我們可以找到System.exit(status)這個方法的說明,代碼如下:

 

  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.     } 

註釋中說的很清楚,這個方法是用來結束當前正在運行中的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)是回到最上層

示例

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章