简体   繁体   English

当Java程序突然退出时,是否可以执行某些操作?

[英]Is it is possible to do something when the Java program exits abruptly?

I need to record an log if the program exited abruptly or with any exception. 如果程序突然退出或有任何异常,我需要记录日志。 For example, when someone presses Ctrl+C while running program, I need to log that it exited abruptly. 例如,当某人在运行程序时按下Ctrl+C时,我需要记录它突然退出。 How can I do this? 我怎样才能做到这一点?

You can try and use a shutdown hook for this. 您可以尝试使用关闭钩子 From the documentation, the hook will be executed under the following circumstances: 从文档中,钩子将在以下情况下执行:

  • The program exits normally 该程序正常退出
  • The VM is terminated VM已终止

This covers your ^C situation, but will doubtfully cover situations like the machine being unplugged (barring some sort of redundant hardware on the machine). 这涵盖了你的^C情况,但无疑会涵盖机器被拔掉的情况(除非机器上有某种冗余硬件)。

Here are some notes about the design. 以下是有关设计的一些注意事项。

Crude example: 原油示例:

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        System.out.println("System was shutdown");
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM