Re-throwing exceptions in C#

November 21st, 2005

I recently came across a bit of client code for logging exceptions and it occurred to me that some people might not know how to properly re-throw exceptions:

Say you have a try...catch block, and in your catch you do something with the Exception, such as log it, then want a higher-up exception handler to take care of it. In such a case, you should NOT use:

...
catch (Exception ex)
{
// log the exception...
throw ex;
}

If you do, the Exception you throw will have a stack frame starting at the current point, i.e. the logging block, and not where it was originally thrown. Rather, you should use the throw; syntax (i.e. “throw” with no exception following it) which is a special version of exception throwing which will re-throw the currently handled exception without creating a new one, resetting the exception stack frame, etc. Like this:

...
catch (Exception ex)
{
// log the exception...
throw;
}

The relevant MSDN documentation:

C# Language Specification: The throw statement

A throw statement with no expression can be used only in a catch block, in which case that statement re-throws the exception that is currently being handled by that catch block.

Comments are closed.