Packaging exception

I often want to add useful information to the exception message. Because the Message property of the Exception class does not have a public configuration tool, one parameter is to wrap the exception that has occurred in another.

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

Is this a bad practice, and if so, what is the alternative?

+4
source share
5 answers

It is better to create a new exception with a pointer to the original exception. You can print both new information and a message from an old exception.

see this information on InnerException

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

This is a standard approach, so Microsoft has built support for this in its Exception class.

+3
source

There is nothing wrong with that, although I would not use the generic Exception class if you have additional information. Debugging problems are simpler, the more specific is your exception.

+3
source

It looks like the Exception.Data property is what I need.

+1
source

The original Exception already has this information. You add a lot here if you are not creating a new Exception , for example. SpecificException , which will make some difference.

0
source

One caveat is that you did not provide any new information for the code that could handle the exception; You only provided something useful to the developer when debugging the problem. It may be all you need, but it seems a little shortsighted.

I prefer not to throw an exception of exactly the same type, especially one as general as an exception, because I could deal with a ConnectionTimeoutException exception, but I was not able to handle a PlanetExplodedException exception. I would not know how to deal with a general exception, except perhaps for registering it.

0
source

All Articles