Rethrowing your exceptions wrong in .NET could erase your stacktrace
You may be erasing your stacktrace if you are catching and rethrowing exceptions the wrong way. This could make debugging a nightmare because you don't know where the exception was originally thrown.
You are erasing parts of the stacktrace if you are catching and rethrowing exceptions like this:
If you catch the rethrown exception and print out the stacktrace, you will notice that there's no mention of the DoWork method where the exception was originally thrown.
That's because it was overwritten when the exception was rethrown.
The correct syntax is to use throw; instead of throw ex;:
If you catch the rethrown exception now and print out the stacktrace, the DoWork method is printed as part of the stacktrace:
Luckily, there's a code analysis rule "CA2200: Rethrow to preserve stack details" that will warn you about this.
Here's the full sample of the code used to demonstrate the issue above: