This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori 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 Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception" Watch "Exception" New topic


Nidhi Jain
Ranch Hand

Joined: Mar 26, 2006
Posts: 31

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

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

Joined: Oct 27, 2005
Posts: 20132

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.

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.
I agree. Here's the link:
subject: Exception
It's not a secret anymore!