【Java基礎】-- System.exit(-1)、System.exit(0)和System.exit(1)區別

System.exit(-1)、System.exit(0)、System.exit(1)區別

1、源碼鏈接

https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#exit(int)

2、說明

  • 所在包:package java.lang
  • 源碼方法:
   /**
     * 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 JVM。如果 status 是非零參數,那麼表示是非正常退出。

  1. System.exit(0) : 將整個虛擬機裏的內容都關掉,內存都釋放掉!正常退出程序。
  2. System.exit(1) : 非正常退出程序
  3. System.exit(-1) :非正常退出程序
 System.exit(0)  or EXIT_SUCCESS;  ---> Success
 System.exit(1)  or EXIT_FAILURE;  ---> Exception
 System.exit(-1) or EXIT_ERROR;    ---> Error

3、總結

  • 區別於 return : return 返回到上一層;System.exit(status) 是回到最上層。
  • System.exit(status):無論 status 爲何值都會退出程序。
  • System.exit(1) :異常退出,一般放在 catch 代碼塊中,當捕獲到異常時,停止程序。
  • System.exit(0); 整個程序正常退出
  • return:“return;” 只能直接回到上一層繼續往下執行,不會直接導致整個程序的停止執行。
  • break:“break;” 只在 switch 語句體和循環體中使用,一個break;語句能退出一個 switch 語句體或循環體,即結束當前循環體。
  • continue:只在循環體應用,“continue;” 代表跳過本次循環,繼續下次循環。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章