When should Throwable be used instead of new Exception?
You should not really catch an exception and throw a new one as general as "new Exception".
Instead, if you wish to bubble up the exception just do the following:
try {
// Do some stuff here
}
catch (DivideByZeroException e) {
System.out.println("Can't divide by Zero!");
}
catch (IndexOutOfRangeException e) {
// catch the exception
System.out.println("No matching element found.");
}
catch (Throwable e) {
throw e; // rethrow the exception/error that occurred
}
It is not good practise, I believe, to catch an exception and throw a new exception instead of the one that was raised to your code block, unless you raise a useful custom exception that provides enough context to elude to the cause of the original exception.
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.