Is it good practice to put exception handling in a constructor?

constructor, exception

Solution

Yes, it's perfectly reasonable. How else would you have a circumstance like this:

class List {
    public List(int length) {
        if(length < 0) {
            throw new ArgumentOutOfRangeException(
                "length",
                "length can not be negative"
            );
        }
        // okay, go!
    }
}

A `List` with negative length is most certainly exceptional. You can not let this get back to the caller and have them think that construction was successful. What's the alternative, a `CheckIfConstructionSucceeded` instance member function? Yucky.

Or what about

class FileParser {
    public FileParser(string path) {
        if(!File.Exists(path)) {
            throw new FileNotFoundException(path);
        }
        // okay, go!
    }
}

Again, this is a throw and nothing else is acceptable.

Problem

Is it legitimate to have exception handling code in a class constructor, or should it be avoided? Should one avoid having exception-generating code in a constructor?

Original source