Cancel MATLAB object creation without exceptions?

In a MATLAB class I write, if the constructor is given 0 arguments, the user is prompted to provide a file with uigetfile

. uigetfile

Returns if the user cancels the invitation 0

. In this case, it makes no sense to make an object. Is there a way to reverse the construction of an object without throwing an exception? If I return early, I get an invalid object that cannot be used. This is what the code looks like:

classdef MyClass
        function self = MyClass(filename)
            if nargin == 0
                filename = uigetfile;
                if filename == 0
                    %cancel construction here
                    return; %I still get a MyClass object with self.filename == []
            self.filename = filename;



However, I'm not sure if using uigetfile

in a constructor is the right thing to do. Maybe it should be the compatibility of another part of my code.


source to share

1 answer

In modern Matlab objects, I don't think it is possible to exit the constructor without returning the constructed object or throwing an error. (In the old style classes, the constructor was indeed allowed to return whatever it wanted, including objects or primitives of other types, and the fact that a person could become a mess.) When the constructor is called, the output argument is already initialized with the object with default property values, so when you call return

it just skips the rest of the initialization and returns an object. If you try to replace something other than the MyClass object, it is an error.

Just rebuild the control flow to pull the GUI code out of the constructor as you speculate at the end. Mixing it with a constructor, especially conditionally, can cause problems. In particular, Matlab expects the zero-arg constructor to always return a scalar object with some default values, because the zero-arg is implicitly expressed when filling elements when expanding an array, etc. It is mainly used as a prototype.



All Articles