Why "throw"; hides the original stack trace

Possible duplicate:
What is the correct way to rethrow an exception in C #?

I want to understand why using "throw ex" hides the original stack trace? What was the main philosophy behind the scene when developing the C # compiler?

+4
source share
2 answers

This is not a C # question, but a CLI design question and comes down to various IL, throw and rethrow .

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

If you specify a throw specific exception, it follows that this exception logically comes from here, now, of this method. If this is not the case, then either:

 throw; 

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

 throw new SomeException(ex); 

and in this case, the caller can get the original stack trace through ex.InnerException .

+9
source

When you encounter an exception, its “place of birth” is somewhere else, and the exception carries a trace on the stack to where it was thrown. Think about this, because throw initializes the stack trace of an instance of the Exception class. So throw ex; initializes the stack trace ex current stack.

0
source

All Articles