A way to throw an exception when the program is forced to exit?

I am trying to make a simple Java wordcounting program.

When it reads Microsoft Office files, it first reads the text of XML files (Microsoft Office files are actually packages of zipped xml files!) And then reads them into a folder named "convert".

I want the "converted" to be removed immediately after the program finishes, so I added

new File("converted").deleteOnExit();

      

which does it well.

However, if the user of the program presses Ctrl + C at the command line, the program will exit the program early and the folder will not be deleted.

I would like to know if there is a way to throw an exception if the program exits. This seems unlikely, because forcing the program to exit will probably stop any code, but I was wondering if this is possible. Then I can handle the exception and end the program so that the directory is deleted. I mean, I can add this:

catch(ExitException e) {    // if the exception is called "ExitException"
    System.err.format("Program ended unexpectedly.%n");
    System.exit(-1);        // this line so that the folder can delete
}

      

(As I understand it, the folder is only deleted when called System.exit()

. Correct me if I'm wrong.)

Thank.

+3


source to share


1 answer


There is really no way to throw an exception in ^C

(Control C), but you can run the code when the program exits in some way like below.

Try using disconnect hooks: Runtime.getRuntime().addShutdownHook()

should work even on ^C

.

Note that this will not do very specific cases as defined there ( SIGKILL

), but it will handle the most minor things.



Try this instead (run it once at some point in your program):

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        try {
            new File("converted").delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

      

And get rid of yours new File("converted").deleteOnExit();

.

+1


source







All Articles