8

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Just guessing: maybe sometimes people still try to log exceptions somehow; and maybe that is easier if you use some of your own custom type exceptions; and so you allow for such things to be wrapped around a Throwable. Or maybe, the language papas and mamas just didn't think that one through. – GhostCat May 04 '16 at 17:44
  • JAVADoc syas: *"An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions."* But it does not forbid you from catching them. – user2004685 May 04 '16 at 17:44

2 Answers2

4

I guess it's basically because:

  1. it's not recommended to handle an Error but it's not forbidden.

  2. 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.

M A
  • 71,713
  • 13
  • 134
  • 174
3

IMHO, Exception Classes takes Throwable as parameter, because some libraries or APIs might create their own type that extends Throwable, and then your Exception Handler need to be able to deal with those as well.

Also you can throw a Throwable not necessarily an Exception, This makes it very easy to throw something that is a custom type of Program Failure, and based on that it will have it's level of 'recoverability'.

For your custom Exception classes, I think it depends on the granularity you need when handling exceptions, most common cases would gracefully handle Throwables, Because you may not be able to recover from an error, but you still to notify users that it happened.

engma
  • 1,849
  • 2
  • 26
  • 55