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.

Published Tuesday, November 30, 2004 10:56 AM by dotnetboy2003

Comments

# re: Throw vs. Throw ex

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

Tuesday, November 30, 2004 11:16 AM by Ron Krauter

# re: Throw vs. Throw ex

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!

Wednesday, April 25, 2007 11:03 AM by CptBongue