When to catch java.lang.Error?
Generally, never.
However, sometimes you need to catch specific errors.
If you're writing framework-ish code (loading 3rd party classes), it might be wise to catch LinkageError
(no class def found, unsatisfied link, incompatible class change).
I've also seen some stupid 3rd-party code throwing subclasses of Error
, so you'll have to handle those as well.
By the way, I'm not sure it isn't possible to recover from OutOfMemoryError
.
In multithreaded environment, you most often want to catch it! When you catch it, log it, and terminate whole application! If you don't do that, some thread that might be doing some crucial part would be dead, and rest of the application will think that everything is normal. Out of that, many unwanted situations can happen. One smallest problem is that you wouldn't be able to easily find root of the problem, if other threads start throwing some exceptions because of one thread not working.
For example, usually loop should be:
try {
while (shouldRun()) {
doSomething();
}
}
catch (Throwable t) {
log(t);
stop();
System.exit(1);
}
Even in some cases, you would want to handle different Errors differently, for example, on OutOfMemoryError you would be able to close application regularly (even maybe free some memory, and continue), on some others, there is not much you can do.
Generally you should always catch java.lang.Error
and write it to a log or display it to the user. I work in support and see daily that programmers cannot tell what has happened in a program.
If you have a daemon thread then you must prevent it being terminated. In other cases your application will work correctly.
You should only catch java.lang.Error
at the highest level.
If you look at the list of errors you will see that most can be handled. For example a ZipError
occurs on reading corrupt zip files.
The most common errors are OutOfMemoryError
and NoClassDefFoundError
, which are both in most cases runtime problems.
For example:
int length = Integer.parseInt(xyz);
byte[] buffer = new byte[length];
can produce an OutOfMemoryError
but it is a runtime problem and no reason to terminate your program.
NoClassDefFoundError
occur mostly if a library is not present or if you work with another Java version. If it is an optional part of your program then you should not terminate your program.
I can give many more examples of why it is a good idea to catch Throwable
at the top level and produce a helpful error message.
Never. You can never be sure that the application is able to execute the next line of code. If you get an OutOfMemoryError
, you have no guarantee that you will be able to do anything reliably. Catch RuntimeException and checked Exceptions, but never Errors.
http://pmd.sourceforge.net/rules/strictexception.html