File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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

Extend an own Exception with an error code

Oliver Brocker

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

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

Yuval Goldstein

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.

Oliver Brocker

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

Joined: Oct 27, 2005
Posts: 20276

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

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Extend an own Exception with an error code
It's not a secret anymore!