7

Possible Duplicate:
What is the proper way to re-throw an exception in C#?

I want to understand why the "throw ex" usage hides the original stack trace? What was the fundamental philosophy behind the scene when designing c# compiler?

Community
  • 1
  • 1
mkus
  • 3,357
  • 6
  • 37
  • 45
  • 3
    are you aware of the fact that you can use `throw;` if you want to re-throw the original exception along with the original stack trace? – Adam Aug 13 '12 at 09:25
  • @codesparkle yes, I aware of "throw" usage. But I just want to learn the reason? – mkus Aug 13 '12 at 09:26
  • In that case it's not really clear what you're actually asking. "Why is there a command that throws with a new stack trace"? Because the designers considered that such a thing would be useful enough to justify the cost of building it <=== but this is the answer to every such question, making it not particularly enlightening. What do you actually want to know? – AakashM Aug 13 '12 at 09:30
  • Nope, this question is not exact duplicate of any other question in the stackoverflow.com by now. I know the best usage and differences between throw; and throw ex; but I just want to learn why the c# architects design in that way. – mkus Aug 14 '12 at 14:48

2 Answers2

12

This isn't actually a C# question, but rather a CLI design question, and comes down to the different IL instructions, throw and rethrow.

Basically, throw ex; (for any ex, even the original) is an IL throw, where-as throw; is an IL rethrow.

If you are specifying a specific exception to throw, it follows that this exception is logically originating from here, now, this method. If that isn't the case, then either:

throw;

rather than throw ex;, or: wrap the exception in another exception, so you preserve the original exception and show where the new one came from:

throw new SomeException(ex);

in which case the caller can obtain the original stack trace via ex.InnerException.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • "`throw ex` is a criminal offense" [is catchy](http://stackoverflow.com/questions/178456/what-is-the-proper-way-to-re-throw-an-exception-in-c) but it doesn't describe _why_ it's criminal. Your explanation of the IL `throw` and `rethrow` helped me understand. Thank you. – twip Aug 02 '14 at 02:55
2

When you catch an exception its "birth place" is somewhere else and the exception carries in the stack trace up to the place where it was thrown. Think about it as throw initializes the stack trace of an instance of Exception class. So throw ex; initializes the stack trace of ex with the current stack.

Karel Frajták
  • 4,389
  • 1
  • 23
  • 34