These are not the Same Thing

In C#, the following two pieces of try-catch code rethrowing are not equivalent. Don’t do the first one; the second one is where it’s at.

try{…}
catch (exception ex)
{

throw ex;

}

try{…}
catch
{

throw;

}

This is because when you rethrow the exception, you’re actually creating a new exception, and the stack trace will show your method as the originator of the exception that you caught and rethrew. The throw ex; syntax is just compiler shorthand and gets expanded into throw new exception(ex);, much like ? : turns into an if-then-else as it’s converted to IL.

Now, you might be tempted to use this technique to mask a call stack, so say an external customer doesn’t need to see the internals of your assembly in the form of a call stack. However, wouldn’t it be more prudent to create a new exception, one where you can customize the message to include your own text and additional information? Perhaps you could even a throw a custom exception of your own? Both are much better ideas, in my book.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>