wood burning stoves*
The moose likes Beginning Java and the fly likes Extend an own Exception with an error code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Extend an own Exception with an error code" Watch "Extend an own Exception with an error code" New topic
Author

Extend an own Exception with an error code

Oliver Brocker
Greenhorn

Joined: Jun 11, 2008
Posts: 15
I searched the web but I don't find someone who had the same idea. So maybe it's a stupid idea?

In my program I get data and validate it. If the data is invalid I throw an exception. Somewhere I catch that exception.


Now I want inform the user why the data is invalid. Not with the error message but also with an error code. But how...?

So I had the idea to expand my MyException class.
When I catch that exception I can use getErrorCode to acces it.
But I'm suprised that I never see that before. Is that a bad solution? Is something like that frowned upon?
[ August 08, 2008: Message edited by: Oliver Brocker ]
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3420
    
  12
No. That's a perfectly reasonable thing to do.


Joanne
Yuval Goldstein
Greenhorn

Joined: Dec 27, 2006
Posts: 18
Thats a good idea, many use it.

Also, I use to keep enum values inside my exception and when passing arguments to the exception construction I pass a value which is one of the enum value.
If you are on this issue I have couple of more improvements: use the enum value as a key for a message bundle message to your log or even show it to the user.
Further more, if the exception translated to an error shown to the user on the presentation level and you want to be able to trace it back to your logs, you can generate a numeric id and tell the user something like:
"If you wish to contact our support-> this is the error number you received".
The other part here, is that you need to log this down or write the error details in the database so they can be used later on by the support.
This is useful in login/password flows.

Cheers.
Oliver Brocker
Greenhorn

Joined: Jun 11, 2008
Posts: 15
Thank you both for your fast replies

And a special to Yuval Goldstein for the further hints . I will think about it.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

java.text.ParseException does a very very similar thing with its error offset.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Extend an own Exception with an error code
 
Similar Threads
"Handle or Declare" Rule for Checked Exceptions
Exception
Nested Try Catch Blocks - why doesn't my throw statement work?
checkedException
Exceptions doubt