Search code examples
matlabruntime-errorsubclasssettermatlab-class

Setting subclass property results in an unexpected error


I have an object that has been instantiated as the class NIRFlex which inherits from the serial class. When I attempt to assign a value of 0 to the property Text_mode from the command line:

>> N.Text_mode = 0

I receive the following error:

Error using serial/subsasgn (line 146) 
The name 'Text_mode' is not an accessible property for an instance of class 'serial port objects'.

My class definition, constructor, and set method are as follows:

classdef NIRFlex < serial

    properties
        Text_mode
    end
    methods
        function obj = NIRFlex(port)
            obj = obj@serial(port);
        end

        function obj = set.Text_mode(obj,mode)
            if (mode == 1)||(mode == 2)
                obj.Text_mode = mode;
            else
                error('Invalid Text Mode');
            end
        end
    end
end

If I remove the set method I can assign any arbitrary value I'd like to the Text_mode property at the command line but I need to ensure that the value entered is only 1 or 2.

I reviewed the Subclasses of Built-In Types with Properties document @ MathWorks but could not find an answer.


Solution

  • The only confusing aspect of this problem is that you don't see your custom error message, but instead some other one generated by the serial class.

    The reason this happens is because of the following code in serial.subsasgn, which gets executed in cases such as objects inheriting from serial:

        catch aException
            try
                Obj = isetfield(Obj, prop1, Value);
            catch %#ok<CTCH>
                throw(localFixError(aException));
            end
        end
    

    As you can see, MATLAB initially tries to set the Value of prop1 (0 and Text_mode, respectively), then your internal class throws an error, which is being caught by subsasgn's catch, and replaced by the aException that was generated earlier and has a different reason.

    I can suggest a couple of options:

    • In your set method, if validation fails, instead of throwing an error, issue a warning and set the value to some default value or just mention that it wasn't modified from whatever it was before. This way you workaround MATLAB's "error swallowing" mechanism.
    • Contact MATLAB and ask them to fix this (i.e. make the internal exception reason visible as well).