Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 618
froadie Avatar asked Feb 03 '10 19:02

froadie


People also ask

Is it good practice to throw exception in constructor?

The short answer to the question “can a constructor throw an exception in Java” is yes! Of course, properly implementing exceptions in your constructors is essential to getting the best results and optimizing your code.

Can we handle exceptions in constructor?

Exceptions: Exceptions in Constructors When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.

Is it good practice to throw exception in constructor C++?

An exception should be thrown from a C++ constructor whenever an object cannot be properly constructed or initialized. Since there is no way to recover from failed object construction, an exception should be thrown in such cases.

Is it good practice to throw exceptions?

The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.


1 Answers

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.

like image 185
jason Avatar answered Nov 16 '22 02:11

jason