Two Guys Arguing

Note to self: C# throw; NOT throw ex;

Posted in .net, java, notes_to_self by benjaminplee on 09.02.10

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.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.