例外:比较消息属性以了解它的含义?

Jef*_*rey 2 c# multilingual exception-handling exception

有时在应用程序中,可能会比较异常的Message文本.例如,如果

ex.Message.Contains("String or binary data would be truncated")
Run Code Online (Sandbox Code Playgroud)

然后将为用户显示MessageBox.

这在英语Windows系统上进行测试时有效.但是,当程序在具有不同语言集的系统上运行时,这将不起作用.如何确保只使用英文异常消息?

Pao*_*sco 7

您无法确保异常消息是英文的; 它取决于您的控件背后的系统设置.

通常,您不应解析异常消息,而应依赖异常类型,如果存在,则依赖于错误代码(与语言无关).

作为示例,不是只捕获一个异常类型并解析消息...

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

...您可以使用多个异常处理程序:

try {
    do_something();
} catch (SqlException sql) { 
    MessageBox.Show("An error occurred...");
} catch (SomeOtherException someExc){
    // exception-specific code here...
} catch (Exception exc) { 
    // most generic error...
}
Run Code Online (Sandbox Code Playgroud)


Sør*_*org 6

正如orsogufo所指出的,您应该检查异常类型或错误代码,并且永远不要尝试解析异常消息(消息是针对用户的,而不是针对程序的消息).

在您的具体示例中,您可以执行类似的操作

try {
    ...
}
catch (SqlException ex)
{
    if (ex.Number == 8152) MessageBox.Show(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

(您必须确定要检查的确切错误号.)