简体   繁体   中英

Using a custom exception class

I created this custom exception class. I want to be able to assign errors to moreErrors. when I instantiate SampleException and assign errors to moreErrors, it is always 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.

And while you can't initialize it to IEnumerable<string> (which is abstract) what you can do is initialize it to List<string>. Then you should be good to go.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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