简体   繁体   中英

Catching an exception when terminating a program in JAVA

Is there a way to do this?

I'm coding a program that has to iterate for a very long time, and while doing so it is supposed to write to file. I want to close the stream as soon as I terminate the program manually and by doing so, avoid the risk of loosing data because of the unclosed stream. There should be a way of doing this with exception handling, but I'm not sure. Any kind of suggestion is very appreciated!

Thank you

in main:

try {
   startapp();
} finally {
   closeAll();
}

in closeAll() you do what you do for a safe shutdown The code in the finally block will executed even when exceptions will ocure.

Using exceptions to control program execution the way you are describing is poor design. It's would be much better to use a shutdown hook.

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
       // Close streams here
    }
});

This will handle most normal shutdowns just fine, though in the case of a hard halt (SIGKILL) the shutdown hooks are not guaranteed to be run. But that is no worse than if you were attempting to close the stream via a finally block.

I found a way! I lost so much time with this, without noticing that streams are automatically closed when the program terminates...

Data hadn't been written because I wasn't using the flush() method after the write() method, like this:

out.write(line);
out.flush();

Thank you all for your help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM