This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception" Watch "Exception" New topic
Author

Exception

Nidhi Jain
Ranch Hand

Joined: Mar 26, 2006
Posts: 31
Hi,

Can we create our own exception in java?If yes how can it possible?
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

Yes. By extending java.lang.Exception.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Nidhi Jain
Ranch Hand

Joined: Mar 26, 2006
Posts: 31
I replied the same but in interviews i recived the reply no.....
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19723
    
  20

Then be glad you were turned down, because they obviously didn't know a thing about programming themselves. It would only be a matter of time before you would have sent a story to The Daily WTF

But the above answer is not complete. You can extend Exception, as well as any subclass of Exception. That includes RuntimeException which will make your exception non-checked as well.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jon Parise
Ranch Hand

Joined: Jul 03, 2007
Posts: 81
usually I make a class that extends exception.

The thing that trips people up is that Exception's attributes like message are not accessible in the subclass.

So instead you need to simply overload the constructors of Exception.

Here is the code for an exception I wrote recently:


It's that simple to make a custom exception.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Exception