【Java基础】-- System.exit(-1)、System.exit(0)和System.exit(1)区别

System.exit(-1)、System.exit(0)、System.exit(1)区别

1、源码链接

https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#exit(int)

2、说明

  • 所在包:package java.lang
  • 源码方法:
   /**
     * 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 JVM。如果 status 是非零参数,那么表示是非正常退出。

  1. System.exit(0) : 将整个虚拟机里的内容都关掉,内存都释放掉!正常退出程序。
  2. System.exit(1) : 非正常退出程序
  3. System.exit(-1) :非正常退出程序
 System.exit(0)  or EXIT_SUCCESS;  ---> Success
 System.exit(1)  or EXIT_FAILURE;  ---> Exception
 System.exit(-1) or EXIT_ERROR;    ---> Error

3、总结

  • 区别于 return : return 返回到上一层;System.exit(status) 是回到最上层。
  • System.exit(status):无论 status 为何值都会退出程序。
  • System.exit(1) :异常退出,一般放在 catch 代码块中,当捕获到异常时,停止程序。
  • System.exit(0); 整个程序正常退出
  • return:“return;” 只能直接回到上一层继续往下执行,不会直接导致整个程序的停止执行。
  • break:“break;” 只在 switch 语句体和循环体中使用,一个break;语句能退出一个 switch 语句体或循环体,即结束当前循环体。
  • continue:只在循环体应用,“continue;” 代表跳过本次循环,继续下次循环。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oo寻梦in记

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值