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?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With