Today, while I was sitting with Matan, a new programmer at our team, for a code review - I saw one of the worst practices that each new programmer and even experienced programmers are dealing with during their coding/reading in .Net, the Exception rethrow mechanism.
I would like to show here two code examples for best and worst practices:I wrote this method for further usage:
static void ThrowNotImplementedException (){ throw new NotImplementedException("not implemented causes in here");}
Worst Practice Example:
try { ThrowNotImplementedException();}catch (NotImplementedException nie){ nie.HelpLink = "I am here!!!"; throw nie;}
Best Practice Example:
try { ThrowNotImplementedException();}catch (NotImplementedException nie){ nie.HelpLink = "I am here!!!"; throw;}
If you are looking at those code snippets and say to yourself: what? this one is for beginners, so first - I agree with you, secondly stop talking to yourself!but still there are many programmers that don't remember, or don't even know this case, I want to show you the difference between those two cases:
stack trace results:Worst Practice:
Best Practice:
Pay attention to the difference between the stack traces which the worst practice do not include the method that caused the Exception! Enjoy debugging.
Last minute editing:I opened the ILDASM (my favorite tool) and looked at the difference between those two:throw x; will convert into assembly command named throw.throw ; will convert into assembly command named rethrow.
I hope this article will help you remember the differences.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.