IllegalArgumentException is indeed the answer here, but I would say that you have problems with your design. In fact, your class invariant depends on the state of some external object, which is a violation of encapsulation. It is impossible to determine if your constructor call will succeed without knowing any other object, which will lead to a confusing and frivolous API.
This problem is mitigated somewhat if the list you are referencing is a static final non-modifiable list (see java.util.Collections.unmodifiableList() ) and is contained in the class in question, but I still don't really like it. It is best to encapsulate, if possible, valid parameter values ββin enum , which completely eliminates the need for an exception. I generally don't like the exceptions thrown from the constructors. If you should throw an exception, use the factory method instead.
If an option is not available to you that eliminates the need for an external list, you may need to rethink your design.
source share