开发者

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

开发者 https://www.devze.com 2023-01-09 06:04 出处:网络
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. How can I d开发者_如

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. How can I d开发者_如何学JAVAo 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

This covers your ^C situation, but will doubtfully cover situations like the machine being unplugged (barring some sort of redundant hardware on the machine).

Here are some notes about the design.

Crude example:

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

精彩评论

暂无评论...
验证码 换一张
取 消