C# – Exceptions: Compare Message Property to Know what it Means

cexceptionexception handlingmultilingual

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?

Best Answer

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.)