System.exit()方法的作用

System.exit()方法的作用

原创  2015年06月11日 19:58:12
查看java.lang.System的源代码,我们可以看到System.exit()这个方法等价于Runtime.exit(),代码如下:

    
    
  1. [java] view plain copy
    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表示退出的状态码,非零表示异常终止。注意:不管status为何值程序都会退出,和return 相比有不同的是:return是回到上一层,而System.exit(status)是回到最上层。

System.exit(0):不是很常见,做过swing开发的可能用过这方法,一般用于Swing窗体关闭按钮。(重写windowClosing方法时调用System.exit(0)来终止程序,Window类的dispose()方法只是关闭窗口,并不会让程序退出)。
System.exit(1):非常少见,一般在Catch块中会使用(例如使用Apache的FTPClient类时,源码中推荐使用System.exit(1)告知连接失败),当程序会被脚本调用、父进程调用发生异常时需要通过System.exit(1)来告知操作失败,默认程序最终返回的值返是0,即然发生异常默认还是返回0,因此在这种情况下需要手工指定返回非零。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值