Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

User defined exceptions

 
sridhar lakka
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks in advance.
In java we can create our own exception. And Java exceptions are mainly divided into two Checked and Unchecked if so, the exception which is created by own will be what type (checked/unchecked).

Regards,
Sree
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can choose.

If your new exception class extends java.lang.Exception, it is a checked exception. In general, your user-defined exceptions should be checked exceptions.

If your new exception class extends java.lang.RuntimeException, it is an unchecked exception. Unchecked exceptions are generally for situations that cannot occur, when the code is working properly - i.e. for indicating bugs.

If your new exception class extends java.lang.Error, it is an Error. Errors are for fatal system problems (e.g. out-of-memory) and are unchecked; there are few valid reasons to define a new Error, but it is legal to do so, if you find a reason.
 
Campbell Ritchie
Sheriff
Posts: 48921
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the Exception you create extends RuntimeException (directly or indirectly, eg "WrongCalculationException extends ArithmeticException" counts as RuntimeException because ArithmeticException already extends RuntimeException) = unchecked.

If the Exception you create extends any other sort of Exception and doesn't extend RuntimeException = checked. Example: EthernetWireMissingException extends IOException doesn't extend RuntimeException directly or indirectly.
Another example: SridharsNewException extends Exception = checked.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Peter's description of when to use checked and unchecked fits Sun's intentions when they invented them. That's a perfectly good way to operate and probably good advice for now. But be aware that not everyone agrees and you may well run into applications written with unchecked exceptions. If you find some code like that, read it carefully and see if you think it worked out better or worse in the long run.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic