Java的System.exit()如何与try / catch / finally块一起使用? [英] How does Java's System.exit() work with try/catch/finally blocks?

查看:236
本文介绍了Java的System.exit()如何与try / catch / finally块一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道涉及在try / catch / finally块中返回的令人头疼的问题 - finally中的返回始终是方法的返回,即使try或catch块中的返回应该是执行的返回。

I'm aware of headaches that involve returning in try/catch/finally blocks - cases where the return in the finally is always the return for the method, even if a return in a try or catch block should be the one executed.

但是,同样适用于System.exit()吗?例如,如果我有一个try块:

However, does the same apply to System.exit()? For example, if I have a try block:

try {
    //Code
    System.exit(0)
}
catch (Exception ex) {
    //Log the exception
}
finally {
    System.exit(1)
}

如果没有异常,将调用哪个System.exit()?如果exit是return语句,则System.exit(1)行将始终(?)被调用。但是,我不确定退出的行为是否与返回不同。

If there are no exceptions, which System.exit() will be called? If the exit was a return statement, then the line System.exit(1) would always (?) be called. However, I'm not sure if exit behaves differently than return.

代码处于极端情况下,即使不是不可能,也很难复制,所以我不能写单元测试。我今天晚些时候会尝试进行一项实验,如果我得到一些免费的分钟,但我很好奇,也许有人知道答案,可以提供它,或者我无法运行实验。

The code is in an extreme case that is very difficult, if not impossible, to reproduce, so I can't write a unit test. I'm going to try to run an experiment later today, if I get a few free minutes, but I'm curious anyway, and perhaps someone on SO knows the answer and can provide it before or in case I can't run an experiment.

推荐答案

没有。 System.exit(0)未返回,且未执行finally块。

No. System.exit(0) doesn't return, and the finally block is not executed.

System.exit(int)可以抛出 SecurityException 。如果发生这种情况,将执行finally块 。并且由于相同的主体从相同的代码库调用相同的方法,因此第二次调用可能会抛出另一个 SecurityException

System.exit(int) can throw a SecurityException. If that happens, the finally block will be executed. And since the same principal is calling the same method from the same code base, another SecurityException is likely to be thrown from the second call.

以下是第二种情况的示例:

Here's an example of the second case:

import java.security.Permission;

public class Main
{

  public static void main(String... argv)
    throws Exception
  {
    System.setSecurityManager(new SecurityManager() {

      @Override
      public void checkPermission(Permission perm)
      {
        /* Allow everything else. */
      }

      @Override
      public void checkExit(int status)
      {
        /* Don't allow exit with any status code. */
        throw new SecurityException();
      }

    });
    System.err.println("I'm dying!");
    try {
      System.exit(0);
    } finally {
      System.err.println("I'm not dead yet!");
      System.exit(1);
    }
  }

}

这篇关于Java的System.exit()如何与try / catch / finally块一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆