Preserving the Stacktrace

Exception handling is important enough to get right. And there’s plenty of sample code out there to help you get it right, nonetheless, i come across two major variations:
catch (Exception ex) {
throw;
}

and

catch (Exception ex) {
throw ex;
}

There’s more about catching general Exception but that’s beyond the scope of this post. So, moving right along…

There is one other variation:

catch (Exception ex) {
throw new Exception(ex);
}
But the first two are more interesting. The second (throw ex;) is the least desirable, unless of course you have a good reason to not preserve the stacktrace.

rethrowexception.PNG
Code attached rethrow.txt