When a java program suddenly exits, can you perform some operations?
•
Java
If the program exits suddenly or there are any exceptions, I need to log For example, when someone presses Ctrl C while running a program, I need to record its sudden exit How can I do this?
Solution
You can try using Shutdown hook From the document, the hook will be executed in the following cases:
>Program normal exit > VM termination
This covers your ^ C situation, but it will undoubtedly cover the situation when the machine is unplugged (unless there is some redundant hardware on the machine)
Here are some design considerations
Example of crude oil:
Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("System was shutdown"); } });
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码