Given: Throwable
is Exception
\'s superclass.
When I read texts on writing your own \'exceptions\', I see examples of Throwable
As I heard it when java first came out, the theory was that Throwable might be used for transfer of control in other cases besides exceptions. I've never seen it used that way though (and that's probably a Very Good Thing).
So just catch Exception (or better yet, a more fine-grained exception).
(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.
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
.
Throwable is meant to be only caught by the container or main loop of your program. Most of the time catching stuff below Exception eg Error does not add much capability to a program, after all what can you possible do if a VirtualError other Errors are thrown. Not much except log and continue.
All exceptions are a problem in the end... too say Errors are bugs doesnt mean anything.
Errors are not bugs - they are problems that the host VM is experiencing, eg OutOfMemoryError. Exceptions are a means that the current operation may use to notify that it failed and perhaps provide some diagnosis.
You shouldn't use Exceptions as a "return type" either...
If the condition you're throwing for is common, you are spending a huge amount of resources to return that condition to the calling routine. Exceptions are expensive to construct.
I've seen cases where tight loops that threw exceptions as a "negative" for e.g. ID allocation, this routine occupied about 99% of the CPU time .. when changed to a documented return constant instead, this dropped to 25%.