How to not instantiate a class if the arguments passed to the constructor are wrong


I hope this is not a duplicate. I searched here and there but I couldn’t find an answer. I have a custom class and the constructor demands a certain type of object to be passed to it. I can easily check within the constructor if the object is valid (eg != Nil, etc…) and at the end of these checks I would like to have an option to throw an exception and avoid the object creation. Is throwing an exception the answer? Is there any other better way?

Thank you in advance for your support

if the arguments are invalid… then have the class return itself as nil (or some detectable value), and have the code that requested the class deal with it… not the class itself… since the class can’t do anything if it doesn’t exist…

Good point. Thank you Dave. That should do. As soon as I fix enough to be able to compile I try it

I think you’re talking about a factory method, not a constructor. By the time you get to the constructor, the object is already created. Think of Constructor as more of an Initializer.

May be a solution setting the constructor as private and providing, thus, a Method of convenience for instantiation that checks if arguments are valid?

For a factory method, add a shared method to the class.
Something like NewMyClass( args ) as MyClass. If args are invalid, return nil.
(Just wanted to help clarify the above comments)