Reputation: 103
I need to create an object of some type. The class of the object has just one constructor (one that I've written).
My program receive requests to create instances of an objects with a parameter ID. I want to stop the constructor if the ID parameter contains a char that is not a digit.
I cannot check the parameter before, since I'm not the one who calls the constructor.
Upvotes: 8
Views: 11709
Reputation: 60564
How to solve this depends on what you want to happen when an illegal character is given, which in turn depends on what object we're talking about, and how the consuming library is using it.
The most reasonable thing to do would be to throw an IllegalArgumentException
, and this is what I'd suggest you do.
However, it might make sense to just return null
, too, even though I'd strongly recommend against it (you can't do this directly in the constructor, but you can create a factory method that does this).
Upvotes: 5
Reputation: 8534
Make the constructor private and expose a static factory method, that will validate and return a new instance of the object if the parameter is valid.
Upvotes: 20
Reputation: 49734
The only way to "stop" a constructor is to throw an exception. Bearing in mind of course that the caller is supposed to "know" about this exception and be able to handle the case where the constructor fails.
Throwing an exception from the constructor doesn't stop the object being created though, It just makes the assignment of its reference to a variable fail and the reference unavaliable (and therefore eligible for garbage collection) unless you make the mistake of passing this
to an external method from the constructor itself. (Which you shouldn't do anyway.)
Upvotes: 6