Navigate back home
GalaSoft Laurent Bugnion
.NET: Re-throwing exceptions without amnesia

A discussion on the newsgroup the other day made me realize that our C# guidelines needs an addition. The topic was "Bubbling exception", and the question (originally in VB.NET, but translated here to C#) was:

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

I realized that some programmers don't know that the first version is even possible, and even more programmers don't know that there is indeed a big difference between both versions.

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.


This demo only works on AJAX-enabled web browsers. For more information, contact me.

 Use 'throw;'
 Use 'throw ex;'
 Use inner exception

Stack trace: