System.exit()方法的作用
来源:互联网 发布:淘宝简约男装店铺推荐 编辑:程序博客网 时间:2024/06/11 10:42
转自:http://www.cnblogs.com/xwdreamer/archive/2011/01/07/2297045.html 略加增添
/** * 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.lang.System的源代码,我们可以看到System.exit()这个方法等价于Runtime.exit()。
从方法的注释中可以看出此方法是结束当前正在运行的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,因此在这种情况下需要手工指定返回非零。
示例
在一个if-else判断中,如果我们程序是按照我们预想的执行,到最后我们需要停止程序,那么我们使用System.exit(0),而System.exit(1)一般放在catch块中,当捕获到异常,需要停止程序,我们使用System.exit(1)。这个status=1是用来表示这个程序是非正常退出。
PS:如果有不同见解,请在评论中给出,会尽快答解,共同交流,学习进步!!
阅读全文
0 0
- System.exit()方法的作用
- System.exit()方法的作用
- System.exit()方法的作用
- System.exit(0)及System.exit(1)的作用
- System的exit
- java中System.exit()方法
- java中System.exit()方法
- java中System.exit()方法
- Android 中的finish()、onDestroy()、System.exit()方法的区别
- continue exit 的作用
- .net强制退出主窗口的方法——Application.Exit()方法和System.Environment.Exit(System.Environment.ExitCode)
- Application.Exit()方法和System.Environment.Exit(System.Environment.ExitCode) :.net强制退出主窗口的方法
- 应该知道的System.exit()
- System.exit(0)与System.exit(1)的区别
- system.exit(0)和system.exit(1)的区别
- System.exit(0) 与System.exit(1)的区别。
- System.exit(0)与System.exit(1)的区别
- System.exit(0)和System.exit(1)的区别
- 搭建以太坊私有链多节点环境
- c语言实现socket服务端/客户端通过tcp传送文件
- java 权限
- thinkphp中的M和D方法详解
- 初识spring-boot
- System.exit()方法的作用
- id_rsa.pub的作用和获取id_rsa.pub
- 判断程序是否运行在虚拟机中的代码
- 通过adb和shell 怎样获取Android设备已安装的App
- 《看透springMVC源码》之Tomcat的顶级结构及启动过程
- 运维必备知识
- Android详细的登录注册功能MVP+Rxjava2.0+Retrofit2.0相结合的实战篇章
- Spring Boot + H2 自动建表不支持多单词驼峰命名的问题
- 数据降维处理:PCA之特征值分解法例子解析