使用C#通过消息捕获异常

10

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

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

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;
}

或者有更好的方法来实现这个目标。

if(ex.Message == "...") 只适用于英语环境。 - H H
你的意思是说,如果用户来自西班牙,C#异常会有所不同吗?我认为这取决于服务器的区域设置。 - Loves2Develop
消息是在异常抛出的地方设置的...并且那里的语言环境必须是“en”。 - H H
2个回答

10
为了在检查消息时避免解开堆栈,您可以使用用户筛选的异常处理程序-https://learn.microsoft.com/en-us/dotnet/standard/exceptions/using-user-filtered-exception-handlers。这将维护未经过滤的异常的堆栈跟踪。
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);
}

9
在catch语句中抛出异常本身没有任何问题。但是需要记住以下几点:
使用"throw"而不是"throw ex"重新抛出异常,否则将丢失堆栈跟踪。
来自[创建和抛出异常] 1
不要故意从自己的源代码中抛出System.Exception、System.SystemException、System.NullReferenceException或System.IndexOutOfRangeException。
如果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中保留了原始异常。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接