views:

107

answers:

3

Sometimes in an application, one might compare the Message text of an exception. For instance, if

ex.Message.Contains("String or binary data would be truncated")

then a MessageBox will be displayed for the user.

This works when testing on an English-language Windows system. However, when the program is run on a system with a different language set, then this won't work. How to ensure that only English exception messages are used?

+6  A: 

You cannot ensure that the exception message will be in English; it depends upon system settings behind your control.

In general, you should not parse an exception message, but rather rely on exception types and, if present, error codes (which are language independent).

As an example, instead of catching only one exception type and parsing the message...

try {
    do_something();
} catch (Exception exc) { 
    if (exc.Message.Contains("String or binary data would be truncated"){
        MessageBox.Show("An error occurred...");
    }
}

...you might use multiple exception handlers:

try {
    do_something();
} catch (SqlException sql) { 
    MessageBox.Show("An error occurred...");
} catch (SomeOtherException someExc){
    // exception-specific code here...
} catch (Exception exc) { 
    // most generic error...
}
Paolo Tedesco
+4  A: 

As orsogufo noted, you should check the exception type or error code, and never try to parse an exception message (the message is for the user, not for the program).

In your specific example, you could do something like

try {
    ...
}
catch (SqlException ex)
{
    if (ex.Number == 8152) MessageBox.Show(ex.Message);
}

(You'll have to determine the exact error number(s) to check for.)

Søren Løvborg
currently my numbers are 8152, 207 and 2627
Jeffrey
+3  A: 

Never parse a message designed to be read by humans.

What if they got the grammar wrong and next release they change it

What if they got the grammar wrong, and next release they change it.

What if they got the grammar wrong, and next release they change it?

John Saunders
that's a good point ;)
Jeffrey
Would the downvoter care to explain?
John Saunders