Why catch Exceptions in Java, when you can catch Throwables?

It all depends a bit on what you’re going to do with an Error once you’ve caught it. In general, catching Errors probably shouldn’t be seen as part of your “normal” exception flow. If you do catch one, you shouldn’t be thinking about “carrying on as though nothing has happened”, because the JVM (and various libraries) will use Errors as a way of signalling that “something really serious has happened and we need to shut down as soon as possible”. In general, it’s best to listen to them when they’re telling you the end is nigh.

Another issue is that the recoverability or not from an Error may depend on the particular virtual machine, which is something you may or not have control over.

That said, there are a few corner cases where it is safe and/or desirable to catch Errors, or at least certain subclasses:

  • There are cases where you really do want to stop the normal course of flow: e.g. if you’re in a Servlet, you might not want the Servlet runner’s default exception handler to announce to the world that you’ve had an OutOfMemoryError, whether or not you can recover from it.
  • Occasionally, an Error will be thrown in cases where the JVM can cleanly recover from the cause of the error. For example, if an OutOfMemoryError occurs while attempting to allocate an array, in Hotspot at least, it seems you can safely recover from this. (There are of course other cases where an OutOfMemoryError could be thrown where it isn’t safe to try and plough on.)

So the bottom line is: if you do catch Throwable/Error rather than Exception, it should be a well-defined case where you know you’re “doing something special”.

Edit: Possibly this is obvious, but I forgot to say that in practice, the JVM might not actually invoke your catch clause on an Error. I’ve definitely seen Hotspot glibly gloss over attempts to catch certain OutOfMemoryErrors and NoClassDefFoundError.

Leave a Comment