Home > Net >  Prevent object creation if some conditions are violated
Prevent object creation if some conditions are violated

Time:09-10

In a script I want to create an object of a class only if all the constructor inputs meet some conditions. All the checks are embedded in the constructor itself. Problem is when:

myObj = myClass(input1,input2,...);

is triggered in the script. The object, even when an input doesn't meet the relative condition, is still created eventually with all empty properties.

Inserting the following code within the constructor:

if nargout == 0
   clear obj;
end

prevents the creation of the object, but only when the output is assigned to the ans variable. Otherwise, I get an error.

Is there a way to obtain something like that without adding some code directly into the script (like using try)?

CodePudding user response:

If the constructor throws an error, no object will be created. Use error. You can put a try/catch block around the constructor call if you like.

There is no way AFAIK to have the constructor return normally but produce no object. What would be assigned to its output?

  • Related