views:

67

answers:

5

I frequently want to add useful information to the message of an exception. Since the Message property of the Exception class does not have a public setter one option is to wrap the exception raised in another.

//...
catch(Exception e)
{
 throw new Exception("Some useful information.", e);
}

Is this bad practise and if so what is the alternative?

+2  A: 

It's better to create a new exception, with a pointer to the original exception. You can print out both the new information and the message from the old exception.

see this info on InnerException

http://msdn.microsoft.com/en-us/library/system.exception.innerexception.aspx

This is the standard approach, which is why Microsoft has built in support for this into their Exception class.

Larry Watanabe
So the approach described in the question is the preferred approach?
Ben Aston
Yes, that's right.
Larry Watanabe
I would recommend this answer too, but I would strongly discourage the use of `Exception` itself. Write an exception class of your own that pertains to the specific error conditions it is for. You can then write a constructor that actually concatenates the given message with the `InnerException`’s message.
Timwi
+1 Timwi -- in the past I just wrote one application-specific exception because it was too much maintenance (especially in java with signature changes) but in c# I don't mind.
Larry Watanabe
+3  A: 

There's nothing wrong with doing that, although I would not use the general Exception class if you have more information. Debugging problems is easier the more specific your exception is.

Jacob
+1  A: 

Looks like the Exception.Data property is what I'm after.

Ben Aston
Exception.Data is definitely useful for adding context-specific information. However, it doesn't exist in all languages (notably Java).
Craig Walker
A: 

Original Exception already has that information. You are adding much here unless you create a new Exception e.g. SpecificException which will carry some meaning.

fastcodejava
A: 

The one caveat is that you haven't provided any new information for code that might be in a position to handle the exception; you've only provided something useful to the developer while debugging a problem. That might be all you're after, but it seems a bit shortsighted.

I prefer not to throw an exception of exactly the same type, especially one as general as Exception, because I might be able to deal with a ConnectionTimeoutException but have no way to handle a PlanetExplodedException. I wouldn't know how to deal with a generic exception other than, perhaps, to log it.

JasonTrue