I understand that you are facing an issue where MATLAB converts the error inside your “PreSet” event callback into a warning instead of stopping execution. This occurs because MATLAB handles errors inside event callbacks differently, often preventing them from stopping property changes.
To resolve this, you can explicitly revert the property change inside the callback before throwing the error. Kindly refer to the following corrected implementation:
classdef MyClass < handle
properties(SetObservable)
Value
end
properties
locked = false;
end
methods
function obj = MyClass()
add_listeners(obj);
end
function add_listeners(obj)
mc = metaclass(obj);
mp = mc.PropertyList;
for run = 1:length(mp)
if mp(run).SetObservable
addlistener(obj, mp(run).Name, 'PreSet', @obj.handle_preset_event);
end
end
end
function handle_preset_event(obj, prop, event)
if obj.locked
event.Source.(prop.Name) = event.AffectedObject.(prop.Name); % Revert change
error('myclass:property_locked', ...
['Property ' prop.Name ' cannot be changed; class instance is locked.']);
end
end
end
end
Here, the “PreSet” listener is added for all “SetObservable” properties in the constructor. Also, the “handle_preset_event” function checks if locked is true. If locked, it explicitly reverts the property change before throwing an error, ensuring MATLAB does not override it with a warning.
With these changes, MATLAB will prevent modifications when the object is locked, and an actual error will be thrown instead of a warning.
For further reference on MATLAB “event listeners”, kindly refer to following documentation:
Cheers & Happy Coding!
