c# - 在哪里/如何存储或处理大量自定义异常?

标签 c# .net exception

假设我想做一些自定义异常(exception)。我想拥有更多。我可以为每个新异常创建一个新类,但是还有另一种方法可以做到这一点吗?如果我必须始终创建一个新类,那么将它们存储在哪里?它只是在项目的根文件夹中看起来不太好。

嗯,还有另一个问题:如果某些异常是相同的,只是异常的名称发生了一点变化,我该怎么办?假设异常 A 看起来像这样:

    [Serializable()]
    public class ExceptionA: Exception, ISerializable
    {
        public ExceptionA() : base() { }
        public ExceptionA(string message) : base(message) { }
        public ExceptionA(string message, System.Exception inner) : base(message, inner) { }
        public ExceptionA(SerializationInfo info, StreamingContext context) : base(info, context) { }
    }
}

另一个是一样的,只是另一个名字:

    [Serializable()]
    public class ExceptionB: Exception, ISerializable
    {
        public ExceptionB() : base() { }
        public ExceptionB(string message) : base(message) { }
        public ExceptionB(string message, System.Exception inner) : base(message, inner) { }
        public ExceptionB(SerializationInfo info, StreamingContext context) : base(info, context) { }
    }
}

等等。我真的必须总是 创建一个新类并粘贴相同的代码吗?有什么建议吗?

最佳答案

I could create for every new exception a new class, but is there another way to do this?

不,没有别的办法。如果你想创建一个新的异常类型,你需要一个新的类。

where to store them?

在所有需要使用它们的代码都可以访问的位置。

what am I doing if some exceptions are the same, just the name of the exception is changing a little bit?

是的,仍然需要创建一个新类 - 尽管您可以从现有异常类派生新类。

关于c# - 在哪里/如何存储或处理大量自定义异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12298598/

相关文章:

c# - 如何在 conversionType 为十进制且输入为 "40.00"时使用 Convert.ChangeType()

java - 应用程序崩溃但方法仍然有效?

c# - 从 Powershell 获取 Azure Active Directory 访问 token

.net - 代理对检测失败

.net - 如何在动态 linq 查询中使用 "contains"或 "like"?

java - "javax.swing.JPanel cannot be cast"异常,令人困惑

delphi - 为什么重新引发 Exception 对象时,其更改会丢失?

c# - nunit resharper 预期异常测试

c# - Initialize 方法是一种代码味道吗?

c# - 如何在 ServiceStack 自托管中设置静态文件的根路径