---
title: ". System.exit(0)和System.exit(1) 和return  区别"
author: "usenrong"
date: "2013-01-30T08:38:24Z"
tags: ["Java", "虚拟机"]
categories: ["编程语言"]
slug: "system-exit-0-system-exit-1-return"
draft: false
lastmod: "2013-01-30T08:38:24Z"
id: 1779457
url: "https://sunrysoft.iteye.com/blog/1779457"
---

1、System.exit(0)和System.exit(1)有什么区别？  
2、在什么情况下执行System.exit()不会抛出异常？如果抛出了SecurityException异常，一般是因为什么原因？  
3、如果我想中止当前运行的java程序，除了执行System.exit()还能用什么方法？

 

 

1。程序返回值不同。  
2。抛出SecurityException是因为你调用了不允许的操作。比如在Applet中操作本地文件，或者在RMI程序中操作不允许的文件。Sun对于这个有专门的文章和解决方法。  
3。对于java程序，运行System.exit()会终止JVM，所以Servlet和Applet中都不应该显示调用这个方法。

 

2個同為exit  
public static void exit(int status)终止当前正在运行的 Java 虚拟机。参数用作状态码；根据惯例，非零的状态码表示异常终止。零状态是终止整个程序。

 

 

 

如果在main方法中System.exit(0)与return 没有区别，都是终止程序。

如果是别的方法,那System.exit(0)直接终止程序,就算后面有代码也不执行了  
而return则返回至调用该方法的地方,如果后面还有代码则继续执行

 

## 2.解析

查看java.lang.System的源代码，我们可以找到System.exit(status)这个方法的说明，代码如下：

 

/\** * Terminates the currently running Java Virtual Machine. The * argument serves as a status code; by convention, a nonzero status * code indicates abnormal termination. * &lt;p&gt; * This method calls the &lt;code&gt;exit&lt;/code&gt; method in class * &lt;code&gt;Runtime&lt;/code&gt;. This method never returns normally. * &lt;p&gt; * The call &lt;code&gt;System.exit(n)&lt;/code&gt; is effectively equivalent to * the call: * &lt;blockquote&gt;&lt;pre&gt; * Runtime.getRuntime().exit(n) * &lt;/pre&gt;&lt;/blockquote&gt; * * @param status exit status. * @throws SecurityException * if a security manager exists and its &lt;code&gt;checkExit&lt;/code&gt; * 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是非零参数，那么表示是非正常退出。

 

1. System.exit(0)是将你的整个虚拟机里的内容都停掉了 ，而dispose()只是关闭这个窗口，但是并没有停止整个application exit() 。无论如何，内存都释放了！也就是说连JVM都关闭了，内存里根本不可能还有什么东西
2. System.exit(0)是正常退出程序，而System.exit(1)或者说非0表示非正常退出程序
3. System.exit(status)不管status为何值都会退出程序。和return 相比有以下不同点： return是回到上一层，而System.exit(status)是回到最上层

 

## 3.示例

在一个if-else判断中，如果我们程序是按照我们预想的执行，到最后我们需要停止程序，那么我们使用System.exit(0)，而System.exit(1)一般放在catch块中，当捕获到异常，需要停止程序，我们使用System.exit(1)。这个status=1是用来表示这个程序是非正常退出。