【问题标题】:call finally before system exit最后在系统退出前调用
【发布时间】:2016-04-03 14:29:42
【问题描述】:

如果引发异常并且 catch 正在调用System.exit,谁能告诉我最终如何执行

try {   
} catch (Exception e) {
    System.exit(0);
} finally {
    System.out.println("closing the conn");
}

【问题讨论】:

标签: java


【解决方案1】:

System.exit() 通常永远不会返回,因此您不会在编写时执行 finally 块中的代码。

您可以做到这一点的一种方法是注意您在 catch 块中有一个错误,然后在 finally 块中退出。

boolean error = false;

try {
   // bla bla blaa

} catch (Exception e) {
    error = true;
}
finally {
    if (error)  {
        System.exit(0);
    }
}

另一种方法是添加一个关闭挂钩,该挂钩将在 JVM 退出时被调用。

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Do your shutdown stuff here");
    }
}));

try {
    // bla bla blah     
} catch (Exception e) {
    System.exit(0);
} finally {
}

【讨论】:

  • 这个可以写,但是我想我们已经改了代码,在catch中System.exit之前有没有办法在finally中关闭连接
  • try { connection.open() } catch (Exception e) { System.exit(0); } finally { System.out.println("关闭连接");连接.close() }
  • @user3431510。简短的回答是否定的。我编辑了我的答案并给了你另一个可能的解决方案。
  • 有类似问题,请看answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多