【问题标题】:Cannot Make Custom Exception Class Constructor with Custom Properties无法使用自定义属性创建自定义异常类构造函数
【发布时间】:2018-05-14 21:40:44
【问题描述】:

当我尝试为自定义异常类设置以下构造函数时,我不理解遇到的编译错误:

[Serializable]
        class AuthenticationException : Exception
        {
            public int PracticeID { get; set; }

            public AuthenticationException()
                : base() { }

            public AuthenticationException(string message)
                : base(message) { }

            public AuthenticationException(string message, Exception InnerException)
                : base(message, InnerException) { }

            public AuthenticationException(SerializationInfo info, StreamingContext context) 
                : base(info, context) { }

            public  AuthenticationException(int PracticeID)
                : base(PracticeID)
            {
                this.PracticeID = PracticeID;
            }
        }

我得到的错误如下:

最好的重载方法匹配 'System.Exception.Exception(string)' 有一些无效参数

&

无法从“int”转换为“string”

两者都发生在类的 : base(PracticeID) 部分。

我不明白为什么它在这里寻找一个字符串。

我尝试寻找答案并根据这两个先前提出的问题拍摄

Custom exception with properties

What is the correct way to make a custom .NET Exception serializable?

我不确定我在做什么与导致错误的第一个不同,我尝试读取/复制第二个但我完全迷失了。

这个异常会发生在内循环中,我想在外循环上有一个客户错误捕获块来处理这种特殊情况。

我认为一种解决方法是使用异常类的 Data 属性,并在外部循环的 catch 块中检查是否有一个名为“Authenticate”之类的项的键并在那里处理异常。

我不想这样做,因为那种异常处理是自定义异常类的本意。

【问题讨论】:

  • 问题是接受 Int 的最终构造函数。 Exception 没有接受 int 的构造函数,因此无法以任何合理的方式解析 base(int)。如果您想要自定义属性,请不将它们发送到基类。这些是您的自定义代码的一部分。
  • 您在该构造函数中调用base(PracticeID)。 Exception 类是否包含只接受 int 的构造函数?

标签: c# .net custom-exceptions


【解决方案1】:

基础异常类没有匹配的构造函数。

改为将代码更改为调用空构造函数(选项 A),或者使用 id 提供默认错误消息(选项 B):

[Serializable]
class AuthenticationException : Exception
{
    public int PracticeId { get; }

        // Other constructors

    // Option A
    public AuthenticationException(int practiceId)
        : base()
    {
        PracticeId = practiceId;
    }

    // Option B
    public AuthenticationException(int practiceId)
        : base("Invalid id: " + practiceId)
    {
        PracticeId = practiceId;
    }
}

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2015-09-13
    • 2023-01-22
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多