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");
}
});
精彩评论