Throw vs. Throw ex

Here is an interesting article about throwing exceptions...
(Follow link for full article)

Rethrowing Exceptions ( via Jackie Goldstein's Weblog )

In Java, when you do "throw ex;", ex is being re-thrown as if it wasn't caught at all - no information about re-throwing is ever recorded and original stack trace info is preserved. If you do want to start exception's stack trace from the re-throwing point - oh, that's completely different story, you need to refill exception's stack trace using fillInStackTrace() method.

In .Net however, when you do "throw ex;", ex is being re-thrown, but the original stack trace info gets overriden. The point where exception is re-thrown is now becoming the exception's origin.

Basically MSIL (CIL) has two instructions - "throw" and "rethrow" and guess what - C#'s "throw ex;" gets compiled into MSIL's "throw" and C#'s "throw;" - into MSIL "rethrow"! Basically I can see the reason why "throw ex" overrides the stack trace, that's quite intuitive if you think about it for a moment. But "throw" syntax for "rethrow" instruction is not really intuitive. It smells stack based MSIL, which is obviously under the cover, but actually should be kept there. I guess they wanted to keep number of C# keywords small, that's the reason. So you just better know this stuff - use "throw;" to re-throw an exception in .NET.

Recent Posts

Tag Cloud

2 Comments

  • You da man! This is one of those things that had me confused coming from a Java background. Thanks for clearing it up.

  • I hate to say it, but it is not the slightest bit intuitive.

    Given ex has a "StackTrace" property, throw ex should be = rethrow, where ex is conserved, with all its properties intact

    throw should be an implicit "throw new Exception()" as there really is no indication of what is thrown.

    MS got that one wrong, which explains why so many experienced developers are losing their stacktraces... I'm going to go refactor my code now... thanks for the info!

Comments have been disabled for this content.