Note to self: C# throw; NOT throw ex;
If you need to catch and re-throw the original exception in C# (and possibly other .Net CLR languages) PLEASE, GOD PLEASE, use:
catch(FooException ex) {
// do what you came here to do
throw;
}
NOT:
catch(BarException ex) {
// do what you came here to do
throw ex;
}
While I love being a polyglot developer equally confident developing on the .Net CLR as the JVM, when I am working in a mainstream OO language I still think in Java. Thus my confusion today when I found a several times re-thrown exception’s stack trace only going back as far as the last re-throw. Turns out that explicitly throwing an exception (new or old) sets the originating stack trace location as the point of the throw command, not where the Exception object was created or originally thrown. This is not the same in Java. I like the syntactic sugar implicitly throwing the caught exception, but shouldn’t the behaviors be the same!? Sadly the offending throw anti-pattern is strewn throughout the code I was working with….
** Also, put the damn curly braces on the same line ;-)
*** Several more knowledgeable .Net devs on the team knew this fact, but weren’t 100% sure why; but I found this link which helped.

leave a comment