Given: Throwable
is Exception
's superclass.
When I read texts on writing your own 'exceptions', I see examples of Throwable
being used in the catch
block and other texts show new Exception()
being used in the catch
block. I have yet to see an explanation of when one should use each.
My question is this, when should Throwable
be used and when should new Exception()
be used?
Inside the catch
or else
block using either:
throw throwable;
or
throw new Exception();
Throwable is super class of Exception as well as Error . In normal cases we should always catch sub-classes of Exception , so that the root cause doesn't get lost. Only special cases where you see possibility of things going wrong which is not in control of your Java code, you should catch Error or Throwable .
The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Throwable has two direct subclasses - Exception and Error. The Exception class is used for exception conditions that the application may need to handle.
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.
Throwable is a bad idea because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable. When you do this, nobody knows what kind of Error this method is going to throw, and until you know what is the problem, how can you resolve that.
Always throw an Exception
(never a Throwable
). You generally don't catch Throwable
either, but you can. Throwable is the superclass to Exception
and Error
, so you would catch Throwable
if you wanted to not only catch Exception
s but Error
s, that's the point in having it. The thing is, Error
s are generally things which a normal application wouldn't and shouldn't catch, so just use Exception
unless you have a specific reason to use Throwable
.
(from comments) The issue that brought this up is that I need to pass an 'exception' to a piece of code a coworker is building if a collection does not get built.
In that case, you might want to throw a checked exception. You could throw an Exception
, an appropriate existing subclass of it (except RuntimeException
and its subclasses which are unchecked), or a custom subclass of Exception
(e.g. "CollectionBuildException
"). See the Java Tutorial on Exceptions to get up to speed with Java exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With