Generally speaking you should never write a catch block that catches java.lang.Error
or any of its subclasses including OutOfMemoryError
. The only exception to this would be if you are using a third-party library who throws a custom subclass of Error
when they should have subclassed RuntimeException
. This is really just a work around for an error in their code though.
From the JavaDoc for java.lang.Error
:
An Error is a subclass of Throwable that indicates serious problems
that a reasonable application should not try to catch.
If you are having problems with your application continuing to run even after one of the threads dies because of an OOME you have a couple options.
First, you might want to check to see if it's possible to mark the remaining threads as daemon threads. If there is ever a point when only daemon threads remain in the JVM it will run all the shutdown hooks and terminate as orderly as possible. To do this you'll need to call setDaemon(true)
on the thread object before it is started. If the threads are actually created by a framework or some other code you might have to use a different means to set that flag.
The other option is to assign an uncaught exception handler to the threads in question and call either System.exit()
or if absolutely necessary Runtime.getRuntime().halt()
. Calling halt is very dangerous as shutdown hooks won't even attempt to run, but in certain situations halt might work where System.exit would have failed if an OOME has already been thrown.