Geeks With Blogs


What I do:

Identity Mine

MVVM Light


What I am:

Microsoft Most Valuable Professional, Client Application Development

Microsoft Certified Technology Specialist, Windows Presentation Foundation

WPF disciples


View my profile on LinkedIn

Creative Commons License
Diary of a Code Trotter by Laurent Bugnion is licensed under a Creative Commons Attribution 3.0 Unported License

All source code on this blog is licensed under the MIT license.

Copyright (c) 2006 - 2011 GalaSoft Laurent Bugnion

Laurent Bugnion (GalaSoft) Diary of a Code Trotter
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:
  // Do something
catch ( Exception )
  // Do something
  // 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.
I made a small ASPX page on my site demonstrating this.
Posted on Friday, September 29, 2006 2:53 PM Technical stuff , .NET | Back to top

Comments on this post: .NET: Re-throwing exceptions without amnesia

Comments are closed.
Comments have been closed on this topic.
Copyright © Laurent Bugnion | Powered by: