Under rare circumstances a subclass of Error can be thrown to force its way past poorly-written legacy code that does a blanket catch of Exception.  

For example, picture some legacy source in a library – perhaps you have a very old project with a closed-source JAR file, and the library can't be changed or improved.

Your project classes all implement abstractCalculate() but there are some cases where you want a fatal problem (such as database unavailable) to stop calculations altogether.

Unfortunately the legacy library has a problem where it throws away any exceptions, something like this:

try
{
    abstractCalculate();
}
catch (Exception e)
{
    // there was a problem, but ignore it and continue
}

It is very common for developers to indiscriminately catch Exception types and ignore them, but there is a way around it.

If abstractCalculate() throws a subclass of Error, it will successfully break out of the catch, because Error is not an Exception.

Of course, if the legacy code catches Throwable, you are still in trouble.

In most cases a subclass of RuntimeException is recommended instead of Error unless constrained by the above code.

Trap: Base class 'Error' is never thrown directly by developers because it is not specific enough.  

blog comments powered by Disqus