gopale
gopale

Reputation: 1

Why is it wrong to throw exception in constructor of class

I have a class which has Id assignment at constructor level. I want id parameter to be more than 0. If it is 0 or negative it causes problem so I want to throw exception if value passed does not meet the criteria:

public class Employee
{
    int _id;
    string name;

    public Employee(int id, string name)
    {
        if(id<1) throw new Exception("ID must be positive, greater than 0);
        _id=id;
        this.name = name;
    }
}

Is this the right way to do it?

Upvotes: 0

Views: 1419

Answers (1)

Charles Mager
Charles Mager

Reputation: 26213

It isn't wrong, it's a valid thing to do to protect the invariants of your class. If you didn't do this, it would be possible to create an object in an invalid state, which you wouldn't want.

I would suggest you use a more appropriate exception type, though. Throwing ArgumentOutOfRangeException would be closer to what you're actually communicating to the caller.

From the docs:

An ArgumentOutOfRangeException exception is thrown when a method is invoked and at least one of the arguments passed to the method is not null and contains an invalid value that is not a member of the set of values expected for the argument.

Upvotes: 3

Related Questions