C#通过消息捕获异常

C#通过消息捕获异常,c#,exception-handling,C#,Exception Handling,我需要用我的自定义消息更改特定的系统异常消息 捕获异常并在捕获块内检查系统异常消息是否与特定字符串匹配,如果匹配,则抛出我的自定义异常,这是一种不好的做法吗 try { ... } catch (System.Security.Cryptography.CryptographicException ex) { if (ex.Message.Equals("The specified network password is not correct.\r\n", StringComp

我需要用我的自定义消息更改特定的系统异常消息

捕获异常并在捕获块内检查系统异常消息是否与特定字符串匹配,如果匹配,则抛出我的自定义异常,这是一种不好的做法吗

try
{
    ...
}
catch (System.Security.Cryptography.CryptographicException ex)
{
    if (ex.Message.Equals("The specified network password is not correct.\r\n", StringComparison.InvariantCultureIgnoreCase))
        throw new Exception("Wrong Password");
    else
        throw ex;
}

或者有更好的方法来实现这一点。

在catch语句中抛出异常本身并没有什么错。但是,有几件事需要记住:

使用“throw”而不是“throw ex”重新抛出异常,否则将丢失堆栈跟踪

来自[创建和引发异常]

不要抛出System.Exception、System.SystemException、, System.NullReferenceException或System.IndexAutoFrangeException 故意从您自己的源代码中删除

如果CrytographicException确实不适合您,您可以创建一个特定的异常类来表示无效密码:

try
{
    ...
}
catch (System.Security.Cryptography.CryptographicException ex)
{
    if (ex.Message.Equals("The specified network password is not correct.\r\n",
            StringComparison.InvariantCultureIgnoreCase))
        throw new InvalidPasswordException("Wrong Password", ex);
    else
        throw;
}

请注意原始异常是如何保存在新的InvalidPasswordException中的。

要在检查消息时保存展开堆栈,可以使用用户筛选的异常处理程序-。这将维护未筛选异常的堆栈跟踪

try
{
    // ...
}
catch (System.Security.Cryptography.CryptographicException ex) when (ex.Message.Equals("The specified network password is not correct.\r\n", 
StringComparison.InvariantCultureIgnoreCase))
{
    throw new InvalidPasswordException("Wrong Password", ex);
}

if(例如,Message==“…”)
仅适用于英语地区。您的意思是,如果用户来自西班牙,那么C#异常将有所不同?我认为这取决于服务器的区域设置。消息设置在引发异常的任何位置。。。在那里,语言环境必须是
en