Reputation: 101
I noticed recently that Exception
has several constructors which take Throwable
as a parameter. Throwable
has two subclasses, Error
and Exception
, and generally all documentation indicates that you should not attempt to catch or handle an Error
. Therefore, I am curious why Exception
takes a Throwable
as a constructor parameter instead of an Exception
. This implies that an Exception
could be created with an Error
as its cause and could be handled by the application. Why is this the case?
Should custom Exception
classes then only provide constructors that take Exception
as parameters?
Upvotes: 9
Views: 1592
Reputation: 1959
IMHO, Exception
class constructors accept Throwable
as a parameter because some libraries or APIs might need to create their failure type that extends Throwable
, and then your failure handlers would need to be able to deal with those as well.
Also, you can throw
a Throwable
and not necessarily an Exception. This makes it easy to throw something that is a custom type of program failure, and hence it will have its unique level of recoverability.
For your custom Exception
classes, I think it depends on the granularity you want when handling failures. The convention would be gracefully handled Throwable
s. This is because even though you may not be able to recover from an error, you may still want to notify users that it happened.
Upvotes: 4
Reputation: 72854
I guess it's basically because:
it's not recommended to handle an Error
but it's not forbidden.
it's a good practice to program to the interface anyway, so the parameter type should support the widest range of types by having it as the root interface Throwable
.
Upvotes: 4