Thursday 8 November 2007

Clear Your Compiler Warnings

There’s a minor problem with this code—at least as far as the compiler’s concerned. Can you spot it?
...
catch (Exception ex)
{
// Don’t do anything
}
The problem is this: the ex variable is declared but never used and the C# compiler will warn you of the fact.

warning CS0168: The variable 'ex' is declared but never used

Does this matter in terms of how the code runs? Of course not but what if everyone always did this and the explosion of compiler warnings masked a more important warning relating to something else? Building the wa.com solution spits out 56 warnings—42 of which have to do with variables never being used—and the entire warning mechanism provided by the compiler is therefore of very little use to us. If it weren’t for this mess, someone might have noticed this fairly useful warning before now:

warning CS0162: Unreachable code detected

There’s an easy way to get around this problem when it comes to exceptions... just don’t declare the exception variable. This example does exactly the same thing at runtime but compiles without the warning. If you need to inspect the exception while debugging, use $exception in a watch.
...
catch (Exception)
{
// Don’t do anything
}
For all other warnings to do with undeclared or unassigned variables, delete the offending declarations!

As for the example catch statement above, you all know this is bad, bad, bad (in all but the most extreme circumstances), right? Bugs disappear into black holes like this and a more specific exception, at the very least, should be caught instead. A better way would be to remove the try/catch statement, test thoroughly to flush out the defects in your code, and reserve exceptions for truly exceptional circumstances.

1 comment:

  1. OH ThankYou! I just started at a new company and my first major build generated a massive error log. How big is massive? When converted to WORD for easier screening on ledger paper at 10 pt type it went to 1500 pages. Needless to say, the 2 error lines that pointed out the fatal problem were burried and lost. 90% of the errors are "xxx declared but not used" and "unreachable code".

    ReplyDelete

Spam comments will be deleted

Note: only a member of this blog may post a comment.