Richard Corfield
Richard Corfield

Reputation: 2529

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

We recently had a problem with a Java server application where the application was throwing Errors which were not caught because Error is a separate subclass of Throwable and we were only catching Exceptions.

We solved the immediate problem by catching Throwables rather than Exceptions, but this got me thinking as to why you would ever want to catch Exceptions, rather than Throwables, because you would then miss the Errors.

So, why would you want to catch Exceptions, when you can catch Throwables?

Upvotes: 85

Views: 30580

Answers (15)

Didier A.
Didier A.

Reputation: 4816

The truth is a bit more nuanced. For the most part, Errors indicate a non-recoverable issue with the application where all usage of the application from that point on will be broken. Therefore what you want to do for all Errors is attempt logging/metric publishing, and restart the application.

The only point of catching them would be to attempt logging/metric publishing and then engaging your restart mechanism.

Generally you'd have a process monitoring tool that supervises the Java process itself, and automatically restarts it in case of an erroneous exit, and it might have logging at that level that would log the process error output and would do its own metric reporting or alarming. In that case, you might not need to catch at all. If the Error is thrown in a thread though, you'd need to catch it to proceed to killing the app, otherwise the thread will die and swallow the error. You can also set the UncaughtExceptionHandler to do that.

Finally, some Errors are localized or recoverable. StackOverflowError, ThreadDeath, and AssertionError are the ones I know. In those cases, per-operation/request you can catch those and fail only the request. Make sure you clean up resources held, but otherwise you can reuse the thread even to handle another request/operation. Don't try to recover those in initialization code, because if it's thrown by any of your singleton or simply from application startup, something is wrong in your setup, you can attempt restart but in those cases whenever an Error is thrown in initialization code it's likely you need to fix it and all restart will result in the same issue. So except a restart loop.

Upvotes: 0

LEMUEL  ADANE
LEMUEL ADANE

Reputation: 8846

Why not catch them all? Then log them, at least you know you have an error. So better catch Throwable/s than Exception/s only.

Upvotes: 0

Neil Coffey
Neil Coffey

Reputation: 21815

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.

Upvotes: 68

TofuBeer
TofuBeer

Reputation: 61546

This post won't make the "checked exceptions are bad" people happy. However, what I am basing my answer on is how Java exceptions are intended to be used as defined by the people that created the language.

Quick reference chart:

  • Throwable - never catch this
  • Error - indicates a VM error - never catch this
  • RuntimeException - indicated a programmer error - never catch this
  • Exception - never catch this

The reason you should not catch Exception is that it catches all of the subclasses, including RuntimeException.

The reason you should not catch Throwable is that it catches all of the subclasses, including Error and Exception.

There are exceptions (no pun intended) to the above "rules":

  • Code you are working with (from a 3rd party) throws Throwable or Exception
  • You are running untrusted code that could cause your program to crash if it thew an exception.

For the second one usually it is enough to wrap main, event handling code, and threads with the catch to Throwable and then check the actual type of the exception and deal with it as appropriate.

Upvotes: 2

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67207

From the Java API documentation:

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.

Errors usually are low-level (eg., raised by the virtual machine) and should not be caught by the application since reasonable continuation might not be possible.

Upvotes: 74

Ravi Wallau
Ravi Wallau

Reputation: 10493

There's at least one case when I think you may have to catch a throwable or a generic exception - if you're running a separate thread to perform a task, you may want to know if the "run" method of the thread has catched some exception or not. In that case, you probably will do something like this:


public void run() {
   try {
       ...
   }
   catch(Throwable t) {
       threadCompletionError = t;
   }
}

I am really not sure if it's the best approach, but it works. And I was having a "ClassNotFound" error being raised by the JVM, and it's an error and not an exception. If I let the exception be thrown, I am not sure how to catch it in the calling thread (probably there's a method but I don't know about it - yet).

As for the ThreadDeath method, don't call the "Thread.stop()" method. Call Thread.interrupt and have your thread to check if it was interrupted by someone.

Upvotes: 3

Darron
Darron

Reputation: 21620

A lot of the other answers are looking at things too narrowly.

As they say, if you are writing application code, you should not catch Throwable. You can't do anything about it, so allowing the surrounding system (JVM or framework) to handle these issues is best.

However, if you are writing "system code", like a framework or other low-level code then you may very well want to catch Throwable. The reason is to attempt to report the exception, perhaps in a log file. In some cases your logging will fail, but in most cases it will succeed and you will have the information you need to resolve the issue. Once you have made your logging attempt you should then either rethrow, kill the current thread, or exit the entire JVM.

Upvotes: 10

OscarRyz
OscarRyz

Reputation: 199333

There is no point in catching Error.

Errors are used to indicate something went really wrong in your application and it should be restarted.

For instance one common error is

java.lang.OutOfMemoryError

There is NOTHING you can do when that happens. Is already too late, the JVM has exhausted all its options to get more memory but it is impossible.

See this other answer to understand more about the three kinds of exceptions.

Upvotes: -1

luke
luke

Reputation: 14788

In general it would be reasonable to try to catch Errors if only so that can be properly reported.

However, I believe there are cases when it would be appropriate to catch an Error and not report it. I'm referring to UnsatisfiedLinkError. In JAI the library uses some native libraries to implement most of the operators for performance reasons, however if the library fails to load (doesnt exist, wrong format, unsupported platform) the library will still function because it will fall back into a java only mode.

Upvotes: 1

Scott Stanchfield
Scott Stanchfield

Reputation: 30652

I'll go a slightly different route from others.

There are many cases where you would want to catch Throwable (mainly to log/report that something evil happened).

However, you need to be careful and rethrow anything that you cannot deal with.

This is especially true of ThreadDeath.

If you ever catch Throwable, be sure to do the following:

try {
    ...
} catch (SomeExceptionYouCanDoSomethingWith e) {
    // handle it
} catch (ThreadDeath t) {
    throw t;
} catch (Throwable t) {
    // log & rethrow
}

Upvotes: 5

James
James

Reputation: 2066

Do NOT ever catch Throwable or Error and you should generally not simply catch a generic Exception either. Errors are generally things that most reasonable programs cannot possibly recover from. If you know what is going on, you might be able to recover from one specific error, but in that case, you should catch only that one particular error and not all errors in general.

A good reason not to catch Error is because of ThreadDeath. ThreadDeath is a fairly normal occurrence that can theoretically be thrown from anywhere (other processes like the JVM itself can generate it), and the whole point of it is to kill your thread. ThreadDeath is explicitly an Error rather than an Exception because too many people catch all Exceptions. If you ever were to catch ThreadDeath, you must rethrow it so that your thread actually dies.

If you have control over the source, it should probably be restructured to throw an Exception rather than an Error. If you don't, you should probably call to the vendor and complain. Errors should be reserved for only things that are terminal with no possible way to recover from them.

Upvotes: 2

matt b
matt b

Reputation: 140051

I know it might be counter-intuitive, but just because you can catch all sorts of Exceptions and Throwables and Errors does not mean you should.

Over-aggressive catching of java.lang.Exception can lead to some serious bugs in applications - because unexpected Exceptions never bubble up, are never caught during development/testing, etc.

Best practice: only catch

  1. Exceptions that you can handle
  2. Exceptions that are necessary to catch

Upvotes: 1

cadrian
cadrian

Reputation: 7376

Slightly off topic, but you may also want to look at this very good article about exceptions.

Upvotes: 0

Johannes Weiss
Johannes Weiss

Reputation: 54101

Normally when programming, you should only catch a specific exception (such as IOException). In a lot of programs you can see a very toplevel

try {
    ...
} catch(Exception e) {
    ...
}

That catches all errors which could be recoverable and all those which indicate a bug in your code, e.g. InvalidArgumentException, NullPointerException. You can then automatically send an eMail, display a message box or whatever you like, since the JavaVM itself is still working fine.

Everything derived from Error is something very bad, you can't do anything against. The question is, if it makes sense to catch a OutOfMemoryError or a VirtualMachineError. (It is a error in the JavaVM itself, probably you can't even display a message box or send an eMail then)

You should probably not a class derived from Error, you should derive from Exception or RuntimeException.

Upvotes: 1

Craig P. Motlin
Craig P. Motlin

Reputation: 26758

Usually Errors are problems you cannot possibly recover from, like OutOfMemoryError. There's nothing to do by catching them, so you should usually let them escape, and bring down the virtual machine.

Upvotes: 6

Related Questions