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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With