Don’t rely on exception messages
Tigraine
Daniel Hoelbling talks about programming and technology

Don’t rely on exception messages

August 20, 2010 by Daniel Hoelbling

Since the dotless 1.1 release we are finally able to present you with good error messages, telling you what line/column the problem was encountered etc. This has led to some tests like this one:

public void DivisionByZero()
{
    AssertExpressionError("Attempted to divide by zero.", 5, "20px / 0");
    AssertExpressionError("Attempted to divide by zero.", 14, "1 + 2 - 3 * 4 / 0");
    AssertExpressionError("Attempted to divide by zero.", 6, "1 + 2 / 0 - 3 * 4 / 0");
}

Usually you just check the exception type, but in this case it’s a generic ParseException that has the additional line/column info on it and does not wrap the DivideByZeroException in it’s InnerException. Obviously the above failed on my machine due to my German locale and I was getting a different exception message.

I first tried to set the thread’s culture to en-GB but this only changes how formats are handled, there are no English exception texts installed on a German Windows machine.

The obvious solution then was to not hard-code the exception message but retrieve it from the DivideByZeroException:

[Test]
public void DivisionByZero()
{
    var divideByZeroException = new DivideByZeroException();
    AssertExpressionError(divideByZeroException.Message, 5, "20px / 0");
    AssertExpressionError(divideByZeroException.Message, 14, "1 + 2 - 3 * 4 / 0");
    AssertExpressionError(divideByZeroException.Message, 6, "1 + 2 / 0 - 3 * 4 / 0");
}

Takeaway: Make sure you tests run on all locales if your tests rely on exception messages. Smile