Monday, September 01, 2008

Bubbling exception

When bubbling some exception up to some interface handlers, what is most recommandable:
try
{ // Do something }
 catch ( Exception )  // notice no variable ex
 {// Do something throw; }


 or:

try
    { // Do something }
catch ( Exception ex )
    { // Do something throw ex; }

if you catch an exception and then rethrow that exception using "throw ex;", the effect is actually that a new Exception will be created in the current scope, and the stack trace will be erased. When the exception is finally handled, the stack trace will start at the point where you rethrew it, instead of starting at the exception's origin.

If you catch an exception and the rethrow that exception using "throw;", you re-throw the exact same Exception, and the stack trace is preserved. Your Exception doesn't suffer amnesia, it remembers where it comes from.

Of course, another better known option is to wrap the caught exception in another one, using the Exception.InnerException property.


Blogged with the Flock Browser

No comments: