Preserving the Stack Trace

Rethrowing Exceptions

Normally, if you have to rethrow and existing exception in .NET, you should use the throw keyword without any parameters:

try
{
    // Code that can generate exceptions here
}
catch (Exception ex)
{
    // Do some logging or whatever
    throw;
}

Using throw ex; would cause the stack trace of the exception to be lost, in which case we lose some valuable information. However, this only works inside the catch block that caught the exception in the first place.

Sometimes, you need to rethrow the exception at a later point outside the catch block, but of course we want to preserve the stack trace.

More...