Dealing with exceptions

Exceptions can be the bane of a new programmers life. I’m sure any ASP.NET web developer is familiar with the ‘yellow screen of death which usually means you have a bug

However, typical enterprise code-bases tend to be littered with workarounds for exceptions rather than fixes

Empty catch block

To me this is the equivalent of putting your fingers in your ears and shouting ‘lalala’. If it doesn’t crash the application, who cares right?

However it’s very rare that you would ever want to ignore an exception. If your end users are occasionally getting an ‘Object reference not set to an instance of an object’ error, putting the code in a try catch will stop the application crashing, but you are not fixing the bug, which in this case would be an object being null.

If any other exception occurs other than the one you mean to ignore, you would never know this as the exception is being ignored. Not only that, but the catch will also incur a performance penalty – admittedly not too noticeable, but worth knowing nonetheless

If you really do need to ignore a particular error, don’t succumb to the below…

Pokémon Exception Handling

“Gotta catch ’em all” is an expression that doesn’t really translate well into the world of C#/.NET. This is of course referring to exception handling like the below:

public decimal GetPercentage(decimal value, decimal total)
{
    try
    {
         return value / total * 100;
    }
    catch (Exception x)
    {
         //Something went wrong...
          return -1;
    }
}

The exception that is likely to be thrown here is a DivideByZeroException, so why not catch that specifically?

public decimal GetPercentage(decimal value, decimal total)
{
    try
    {
         return value / total * 100;
    }
    catch (DivideByZeroException x)
    {
         //Something went wrong...
          return -1;
    }
}

By catching the specific exception you expect, you’ll ensure that you’ll still be aware of other bugs

Not logging exceptions

If you have a try/catch, you should always log this in your application. Your future self, and colleagues, will be very grateful when you have a user complaining of a bug you can’t replicate!

Not only should you log an exception details, you should also log any parameters and any other information you think could be useful. For example, parsing an int with int.Parse is quite common in C# – if the input is invalid, you’ll get the generic exception ‘Input string is not in the correct format’. The actual contents of the string being parsed here would make debugging a heck of a lot easier!

Embrace them!

Above all, don’t be scared of exceptions in your application. You can never handle every exception – if a user gets an OutOfMemoryException or StackOverflowException then having the application crash is completely acceptable. There is very little you can do to avoid these, and any attempts to recover may result in more cryptic errors popping up afterwards.