Home > View Post

Make your exceptions as helpful as possible

It's so easy to add value to exceptions that your code throws but the chance is often passed up in favour of a standard message. For example, imagine you have a piece of code that checks the state of something before continuing with a method invocation. We know that a column in a Sudoku cube for example should have 9 cells and it might be prudent to test that in our (very imaginary) Sudoku API.

public bool IsValidColumn(Column column)
{
    // TODO - Check for nulls...
    // If there aren't nine cells in my column, something is wrong
    if (column.Cells.Length != 9)
    {
        throw new InvalidStateException("There should be 9 cells in a column, doofus!");
    }
    
    // TODO - Implement actual logic
    throw new NotImplementedException("The IsValidColumn method has not yet been fully implemented");
}

That will help significantly in debugging if, for some reason, your Column ends up in an invalid state. But we've missed an opportunity to be even more helpful. How about

throw new InvalidStateException(string.Format(
    "There should be 9 cells in a column but this one has {0} cells!", column.Cells.Length));
    
Now, when we're looking through our error logs we know more about the invalid state. If there are zero cells, there's a good chance I'm forgetting to set them up at all. If there are 8 or 10 then there's probably something subtly wrong with one of the for or while loops in the code. I can zero in on the problem.

A classic example where this type of error message often proves exceptionally (no pun intended) useful is the FileNotFoundException, which is kind enough to include the path to the missing file.

Tags: .NET

 
Josh Post By Josh Twist
10:18 AM
12 Feb 2007

» Next Post: Microsoft Office Groove 2007
« Previous Post: Minor foibles with my computing life

Comments are closed for this post.

© 2005 - 2017 Josh Twist - All Rights Reserved.