0

I have a handle class, i.e mclass below, which should be constructed inside another function with corresponding input argument. However, i want to check the input argument of the class constructor inside the constructor of wherever in the class itself, and prevent new object handle being created if input is not desired type.

classdef mclass < handle
    properties
        val
    end
    properties (Dependent)
        sval
    end
    methods
        function obj = mclass(varargin)
            if nargin == 1
                if isnumeric(varargin{1}) && varargin{1} > 0
                    obj.val = varargin{1};
                else
                    errordlg('Invalid input', 'Constructor', 'modal');
                end
            else
                errordlg('No input', 'Constructor', 'modal');
            end
        end
        function s = get.sval(obj)
            s = sqrt(obj.val);
        end
    end
end

However, after calling m = mclass; or m = mclass(0); from Command Window, together with the error dialog, variable m is still created in the Workspace. How can I prevent m being created?

Of course I can check for the input inside my other functions before calling constructor, but is there anyway to make it a "self-check" characteristic of the class?

scmg
  • 1,904
  • 1
  • 15
  • 24

1 Answers1

1

errordlg does not stop program execution. It only displays the dialog. To stop your program additionally you need to issue a call to error. You can combine both and use the following lines which will stop object creation when you issue an error.

function obj = mclass(varargin)
    if nargin == 1
        if isnumeric(varargin{1}) && varargin{1} > 0
            obj.val = varargin{1};
        else
            errordlg('Invalid input', 'Constructor', 'modal');
            error('Invalid input for Constructor of mclass');
        end
    else
        errordlg('No input', 'Constructor', 'modal');
        error('No input for Constructor of mclass');
    end
end
Navan
  • 4,407
  • 1
  • 24
  • 26
  • yes, `error` was one of my workarounds, but could i make it happen totally inside a program? i mean, nothing should be displayed in the command window (especially the ugly `Error using xxx (line yyy)` of `error`), users just need to be informed what did they wrongly enter, they don't need to care about where in which function the error was... – scmg Sep 04 '15 at 22:47
  • 1
    You would then need to use try,catch and wrap class creation inside another function which does the try,catch. I cannot think of another way. – Navan Sep 05 '15 at 05:25