• Post Reply Bookmark Topic Watch Topic
  • New Topic

Best practice for overriding Exception.toString()  RSS feed

 
James Adams
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a custom exception class which includes an optional error code, and I'd like to include this error code in the Exception's toString() output. I assume that this is just a matter of appending the error code to the result of super.toString(), something like this:



Does this look reasonable?

Thanks in advance for your responses.

--James
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would be more idiomatic to supply the error code as part of getMessage(); include the code in your call to super() in your class's constructor. Exception.toString() isn't going to be called often in production code.
 
James Adams
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So when a stack trace is printed the exception's getMessage() is called, instead of toString()? If so then it seems that what I really want to do is to override getMessage() so that the String it returns will include the error code if it is set.

Can you elaborate on what you mean about supplying the error code as part of getMessage() by including the code in the call to super() in the constructor? I already call super(message) in my constructor which takes a message argument, and there's no super() method which takes an integer argument, and besides the error code isn't known at creation time. Obviously I'm confused as to what you're suggesting.

--James
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The error code isn't known when the exception is about to be thrown? Hmmm. Not sure how that could be...

Here's an example of a typical kind of custom exception type I've written:



Does this answer your questions? You could override getMessage(), but the above is really preferable if you can make it work.
 
James Adams
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest. Yes the error code is known at creation time, I don't know what I was thinking. I appreciate your help.

--James
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!