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.
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).