c#通过消息捕获异常

本文关键字:捕获异常 消息 | 更新日期: 2023-09-27 18:02:13

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

捕获异常并在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;
}

c#通过消息捕获异常

要在检查消息时避免展开堆栈,您可以使用用户过滤的异常处理程序- 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);
}

在catch语句中抛出异常本身并没有什么问题。然而,有几件事要记住:

使用"throw"重新抛出异常而不是抛出ex",否则您将失去堆栈跟踪。

选自[创建和抛出异常]1.

不要抛出系统。异常,系统。SystemException,系统。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中如何保留原始异常。