Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "throw ex;" hides original stack trace [duplicate]

Tags:

c#

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?

like image 816
mkus Avatar asked Aug 13 '12 09:08

mkus


2 Answers

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.

like image 113
Marc Gravell Avatar answered Nov 01 '22 16:11

Marc Gravell


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.

like image 44
Karel Frajták Avatar answered Nov 01 '22 15:11

Karel Frajták