Friday, March 19, 2010

"throw" vs. "throw ex"

Here is an interesting bit of C# knowledge I just picked up from a coworker the other day: rethrowing an exception with "throw ex" usually isn't what you want to do. You can do it, and at first glance it works fine, but when you use "throw ex" the stack trace of the exception is erased, making it appear as if the exception originated from your code, making debugging more difficult than it should be.

If you are catching an exception and you want to rethrow the exact same exception, just use "throw;". This will rethrow the exception with the stack trace intact. If you are throwing a new exception, make sure to set the original exception as the inner exception before throwing.

Thanks to this post for making it clear.

No comments: