1

When creating my own exception, are there any benefits that I need to take into account when deciding which super class to extend?

What are the prons and cons of each one of them?

class MyException extends Exception 

vs

class MyException extends Throwable
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
USer22999299
  • 5,284
  • 9
  • 46
  • 78
  • 4
    Take a look at this: http://stackoverflow.com/questions/14891717/custom-exception-class-extends-from-exception-or-thowable or possibly even this: http://stackoverflow.com/questions/498217/when-should-throwable-be-used-instead-of-new-exception – Dan Temple Aug 20 '14 at 06:56
  • 1
    please see here http://stackoverflow.com/questions/2274102/difference-between-using-throwable-and-exception-in-a-try-catch – swingfly Aug 20 '14 at 06:58
  • 1
    You should never have a reason to extend `Throwable` directly. You either extend `Exception`, `RuntimeException` or `Error` (or an already existing subclass of those) – Mark Rotteveel Aug 20 '14 at 07:07

3 Answers3

3

The first one catches all subclasses of Throwable (this includes Exception and Error), the second one catches all subclasses of Exception Class.

Error is programatically unrecoverable in any way and should be avoided as far as catching is concerned, except for logging purposes, which in turn should throw it again. Error should not be caught, except if you are trying for something kinda "catch all" level of a thread.

Exception is programmatically recoverable. Its subclass RuntimeException indicates a programming error and is usually not to be catched as well.

Manish Kr. Shukla
  • 4,447
  • 1
  • 20
  • 35
0

It must extends from Exception, Throwable must be only implemented for Java Virtual Machine Errors and Critical Operative System Error like running out of memory heap space or system block.

Ian
  • 30,182
  • 19
  • 69
  • 107
-1

By catching Throwable it includes things that subclass Error. You should generally not do that, except perhaps at the very highest "catch all" level of a thread where you want to log or otherwise handle absolutely everything that can go wrong. It would be more typical in a framework type application (for example an application server or a testing framework) where it can be running unknown code and should not be affected by anything that goes wrong with that code, as much as possible. see difference-between-using-throwable-and-exception-in-a-try-catch

Community
  • 1
  • 1