实现通用自定义异常的优点和缺点

Kam*_*yar 4 .net c# exception-handling exception custom-exceptions

实现自定义异常的优缺点如下:
创建一个枚举,在其描述中表示错误消息:

public class Enums
{
    public enum Errors
    {
        [Description("This is a test exception")]
        TestError,
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

创建自定义异常类:

public class CustomException : ApplicationException
{
    protected Enums.Errors _customError;
    public CustomException(Enums.Errors customError)
    {
        this._customError = customError;
    }
    public override string Message
    {
        get
        {
            return this._customError!= Enums.Errors.Base ? this.customError.GetDescription() : base.Message;
        }
    }  
}  
Run Code Online (Sandbox Code Playgroud)

GetDescription方法是枚举扩展方法,它使用反射获取枚举描述.这样,我可以抛出异常,如:

throw new customException(enums.Errors.TestError);  
Run Code Online (Sandbox Code Playgroud)

并在catch块中向用户显示如下:

Console.WriteLn(ex.Message);  
Run Code Online (Sandbox Code Playgroud)

我见过MVP推荐的这种方法.这种方法对以下方面有什么好处:

  • 使用泛型异常:抛出新的异常("错误消息");.
  • 使用自定义例外:为任何情况定义自定义例外.例如(WebServiceException班级,AuthenticationException班级等)

这是 MVP推荐的链接.

谢谢.

ale*_*exn 5

就个人而言,我认为这不是一个好主意.

您应该始终抛出特定的例外情况.捕捉同样如此.

我们很容易决定是否要捕获一个WebServiceException或者AuthenticationException,但是使用您的Enum示例,我们必须解析一个字符串以决定是否要捕获它.如果此消息更改会发生什么?

我认为它没有任何好处.对于每种错误类型,您必须创建一个新的Enum成员.为什么不创建一个新类呢?