开发者

Wrapping Exceptions

开发者 https://www.devze.com 2022-12-16 02:31 出处:网络
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 i

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?开发者_StackOverflow社区


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.


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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消