c# - 实现通用自定义异常的优缺点

标签 c# .net exception exception-handling custom-exceptions

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

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

创建自定义异常类:

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

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

throw new customException(enums.Errors.TestError);  

并在 catch block 中将其显示给用户,例如:

Console.WriteLn(ex.Message);  

我见过 MVP 推荐的这种方法。这种方法比以下方法有什么好处:

  • 使用通用异常:throw new Exception("Error Message");。
  • 使用自定义异常:为任何情况定义自定义异常。例如(WebServiceException 类、AuthenticationException 类等)

Here's the link MVP 的推荐。

谢谢。

最佳答案

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

您应该始终抛出尽可能具体的异常。捕捉也是如此。

很容易决定我们是否要捕获 WebServiceExceptionAuthenticationException,但是对于您的 Enum-example,我们必须解析一个字符串来决定是否要捕获与否。如果此消息发生变化会怎样?

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

关于c# - 实现通用自定义异常的优缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6310241/

相关文章:

exception - 发送消息到移动API j2me

Java异常处理概念

c# - 如何更改 MVC C# 中的 URL?

c# - 无法使用独立关联将可选外键设置为空

c# - 有利于性能

.net - Visual Basic圆形进度条

c# - 打印一个数组的内容(代码为一行,用于visual studio Immediate window)

c# - Entity Framework Core 不包含 'Include' 的定义

c# - 在 C# .NET 中编码非 ascii 字符

c# - 抛出异常后应用程序不退出