System.exit()方法的作用

来源:互联网 发布:我朝 知乎 编辑:程序博客网 时间:2024/06/15 10:11
查看java.lang.System的源代码,我们可以看到System.exit()这个方法等价于Runtime.exit(),代码如下:

  1. /** * 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)是回到最上层。

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,因此在这种情况下需要手工指定返回非零。

2 1
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 指甲长了两层怎么办 脚趾甲长了两层怎么办 产妇气血虚没奶怎么办 哺乳期气血不足奶水少怎么办 刚怀孕喝了啤酒怎么办 受风怎么办最快最有效 孕妇后背受风了怎么办 肩膀和后背受风怎么办 手指关节杵肿了怎么办 骨关节退行性变怎么办 疼风脚趾肿了怎么办 痛风脚右侧肿了怎么办 痛风引起的脚肿怎么办 老人腰闪了该怎么办 腰闪了站不起来怎么办 又怕冷又爱上火怎么办 肝上多发小囊肿怎么办 5岁宝宝咳嗽厉害怎么办 5岁宝宝咳嗽有痰怎么办 生川乌外贴中毒怎么办 7个月宝宝流鼻涕怎么办 脸上皮肤毛孔粗大有黑头怎么办 嗓子长了个囊肿怎么办 食管胃粘膜异位怎么办 狗狗肿瘤破了怎么办 婴儿胃食道反流怎么办 小儿胃食道反流怎么办 放疗后咳嗽痰多怎么办 胃息肉是恶性的怎么办 老是胃疼,胃胀怎么办 吃完饭之后胃胀怎么办 胃痛胃胀怎么办能缓解 胃胀不消化怎么办快速解决 便秘肛裂了好痛怎么办 胃消化慢还便秘怎么办 11个月婴儿便秘怎么办 80多岁老人便秘怎么办 狗狗便秘拉不出来怎么办 2个月幼犬便秘怎么办 狗狗便秘怎么办吃什么 痔疮又痛又痒怎么办