public final class System { ... /** * 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)是回到最上層。java
2.System.exit(1):很是少見,通常在Catch塊中會使用(例如使用Apache的FTPClient類時,源碼中推薦使用System.exit(1)告知鏈接失敗),當程序會被腳本調用、父進程調用發生異常時須要經過System.exit(1)來告知操做失敗,默認程序最終返回的值返是0,即然發生異常默認仍是返回0,所以在這種狀況下須要手工指定返回非零。jvm
public static int test(){ int t=0; try { t=1/0; }catch (Exception e){ e.printStackTrace(); System.exit(1); } return t; } public static void main(String[] args) { System.out.println(test()); System.exit(0); } 運行結果爲: java.lang.ArithmeticException: / by zero at com.test.frame.test.socket.nio.TimerServer.test(TimerServer.java:12) at com.test.frame.test.socket.nio.TimerServer.main(TimerServer.java:22) Process finished with exit code 1
由上可知,在catch中jvm強制退出socket