简体   繁体   English

使用自定义异常 class

[英]Using a custom exception class

I created this custom exception class.我创建了这个自定义异常 class。 I want to be able to assign errors to moreErrors.我希望能够将错误分配给更多错误。 when I instantiate SampleException and assign errors to moreErrors, it is always null当我实例化 SampleException 并将错误分配给 moreErrors 时,它始终是 null

What am I doing wrong here?我在这里做错了什么?

        public class SampleException : Exception
        {
            public SampleException(string message):base(message)
            {
            }

            public IEnumerable<string> moreErrors { get; set; }
        }

You could use it like below:你可以像下面这样使用它:

public class SampleException : Exception
{
    public SampleException(string message, List<string> errorList = null) : base(message)
    {
        ErrorList = errorList;
    }

    public List<string> ErrorList { get; set; }
}

and throw exceptions like this:并抛出这样的异常:

throw new SampleException("Error Message", new List<string>() { "Error 1", "Error 2" });

The 'ErrorList' property is null because it has not been initialized to anything. 'ErrorList' 属性是 null 因为它没有被初始化为任何东西。

And while you can't initialize it to IEnumerable<string> (which is abstract) what you can do is initialize it to List<string>.虽然您无法将其初始化为 IEnumerable<string>(这是抽象的),但您可以将其初始化为 List<string>。 Then you should be good to go.那你应该对go好。

    public class SampleException : Exception
    {
        public SampleException(string message) : base(message)
        {
        }

        public List<string> MoreErrors { get; set; } = new List<string>();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM