AE426082
AE426082

Reputation: 633

Cancelling MATLAB object construction without exceptions?

In a MATLAB class I am writing, if the constructor is given 0 arguments, the user is asked to provide a file using uigetfile. If the user cancels the prompt, uigetfile returns 0. In that case it makes no sense to make the object. Is there some way of cancelling the object construction without throwing an exception? If I do an early return I get a malformed object that cannot be used. Here is what the code looks like:

classdef MyClass
    methods
        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 == []
                end
            end   
            self.filename = filename;
        end
    end

    properties
        filename;
    end
end

However I am unsure if using uigetfile in the constructor is the right thing to do. Maybe it should be the resposibility of another part of my code.

Upvotes: 3

Views: 345

Answers (1)

Andrew Janke
Andrew Janke

Reputation: 23858

In modern Matlab objects, I don't think it's possible to get out of the constructor without either returning a constructed object or throwing an error. (In the old style classes, the constructor was actually allowed to return whatever it wanted, including objects or primitives of other types, and oh man could that turn in to a mess.) When a constructor is called, the output argument is already intialized with an object with the default property values, so when you call return there, it just skips the rest of initialization and returns the object. If you try to replace out with something besides a MyClass object, that's an error.

Just reorganize the control flow to pull the GUI code out of the constructor, like you're speculating on at the end. Mixing it in to the constructor, especially conditionally, can cause problems. In particular, Matlab expects the zero-arg constructor to always return a scalar object with some sort of default values, because the zero-arg gets called implicitly when filling in elements during array expansion and so on. It's basically used as a prototype.

Upvotes: 5

Related Questions