Can we stop the constructor from starting?

I need to create an object of some type. An object class has only one constructor (the one I wrote).

My program receives requests to instantiate objects with a parameter identifier. I want to stop the constructor if the ID parameter contains a char, which is not a digit.

I can not check the parameter before, since I'm not the one who calls the constructor.

+8
java constructor
source share
3 answers

How to solve this depends on what you want when an illegal symbol is specified, which, in turn, depends on what we say and how the consumption library uses it.

The most sensible thing to do is to throw an IllegalArgumentException , and this is what I suggest you do.

However, this may make sense just return null , even if I strongly recommend against it (you cannot do it directly in the constructor, but you can create a factory method that does this).

+4
source share

Make the constructor private and set the static factory method, which will check and return a new instance of the object, if this parameter is valid.

+19
source share

The only way to β€œstop” the constructor is to throw an exception. Given, of course, that the caller must β€œknow” about this exception and be able to handle the case where the constructor fails.

Throwing an exception from the constructor does not stop the object being created, but only makes the assignment of the variable reference unsuccessful, and the link is unavailable (and therefore has the right to garbage collection) if you make a mistake by passing this external method from the constructor itself. (What you shouldn't do anyway.)

+6
source share

All Articles