开发者

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. 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜