When to catch java.lang.Error? When to catch java.lang.Error? java java

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.


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


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.