天天看點

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

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

1、源碼連結

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);
    }      
  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;” 代表跳過本次循環,繼續下次循環。