Thursday, January 29, 2004

Anonymous Exception Catching

I was going through the FlexWiki code the other day, and I saw this block of code:


catch (FormatException ex)
{
    ex.ToString(); // shut up compiler;
}


I've seen this before: you know an exception is going to be thrown, and you also know that it's safe to ignore it. (You should think twice about doing this, but sometimes it's unavoidable.) And that annoying little call to ToString() winds up in there because otherwise the compiler pitches a warning about there being an unreferenced local variable. Although it's only a warning, and could in theory just be ignored, many build systems wisely compile their code with the warning level set to maxiumum, which would actually turn this into a compilation error.


The code often gets written this way because developers don't realize that you can safely do this:


catch (FormatException)
{
}


Notice that there's no exception variable. This will compile just fine, and it does exactly the same thing the previous code does - silently throws the exception away. Only now we don't have that confusing extra line of code in there, and the compiler won't complain about unused variables.


I should point out that there actually is one case where you might want to leave that line of code in. If you want to be able to view the exception while debugging, it's convenient to have a variable to examine in the debugger. However, in that case, I would recommend using this code instead:


catch (FormatException ex)
{
    Debug.WriteLine(ex.ToString());
}


This has the advantage that under a Debug build, you can still set a breakpoint and examine the exception. However, because System.Diagnostics.Debug.WriteLine is marked with the [Conditional(”Debug”)] attribute, it will not be compiled at all under a Release build - it'll be like that line of code isn't even there.


This is a slick little bit of compiler magic that you can take advantage of in your own code to write functions that disappear from your Release builds. Check out the documentation on the Conditional attribute for more information.

4 comments:

  1. I didn't know :)

    Thanks

    ReplyDelete
  2. We aim to please. :)

    ReplyDelete
  3. Yeah -- I didn't know either (and I'm probably the one who put most of those into the FlexWiki source).

    Thanks!

    ReplyDelete
  4. I should be thanking you: I've been having a lot of fun working on FlexWiki. Hopefully some of the stuff I'm baking right now will repay some of your effort.

    ReplyDelete