Best practices: throwing exceptions from properties

后端 未结 8 1932
生来不讨喜
生来不讨喜 2020-11-29 16:18

When is it appropriate to throw an exception from within a property getter or setter? When is it not appropriate? Why? Links to external documents on the subject would be he

8条回答
  •  盖世英雄少女心
    2020-11-29 17:08

    I had this code where I was unsure of which exception to throw.

    public Person
    {
        public string Name { get; set; }
        public boolean HasPets { get; set; }
    }
    
    public void Foo(Person person)
    {
        if (person.Name == null) {
            throw new Exception("Name of person is null.");
            // I was unsure of which exception to throw here.
        }
    
        Console.WriteLine("Name is: " + person.Name);
    }
    

    I prevented the model from having the property being null in the first place by forcing it as an argument in the constructor.

    public Person
    {
        public Person(string name)
        {
            if (name == null) {
                throw new ArgumentNullException(nameof(name));
            }
            Name = name;
        }
    
        public string Name { get; private set; }
        public boolean HasPets { get; set; }
    }
    
    public void Foo(Person person)
    {
        Console.WriteLine("Name is: " + person.Name);
    }
    

提交回复
热议问题