I don’t understand Matlab’s behaviour in the example below. On deserialization, it sets the properties of the object. This causes set.name to be executed. For the purpose of the example, I have constructed a case where an error is thrown in this method. In the first deserialization, the error is ignored and unhandled; the function simply stops execution at the error, code after the error is not executed. On the second deserialization, I have set dbstop if error, and now the error is triggered as I would expect. Questions follow below the example.
>> clear all;
>> dbstatus;
>> type Tester.m;
classdef Tester < handle
properties
name;
end
methods
function self = Tester()
disp('Creating Tester object');
end
function set.name(self, val)
global allnames
if isequal(allnames, [])
allnames = {};
end
if any(strcmp(allnames, val))
fprintf(1, 'Name already exists. Will issue error.\n');
error('Error: duplicate name %s', val);
fprintf(1, 'Still here?\n');
else
self.name = val;
allnames = [allnames self.name];
end
end
end
end
>> t = Tester();
Creating Tester object
>> t.name = 'abc';
>> save('/tmp/fubar.mat', 't');
>> load('/tmp/fubar.mat')
Name already exists. Will issue error.
>> dbstop if error
>> load('/tmp/fubar.mat')
Name already exists. Will issue error.
Error using Tester/set.name (line 18)
Error: duplicate name abc
18 error('Error: duplicate name %s', val);
K>> dbquit
- Should I be surprised at this behaviour?
- Is this MATLAB™ being strange, or would other programming languages engage similar behaviour?
- Is there a good reason to behave like this?
Probably the deserialization code uses a
try-catchconstruct that does not rethrow the errors. I can see some uses for this, as faults in the load code would at least give you partial access to your data. On the other hand, it should warn you when it does something like this.When it really can’t load the data (this happens e.g. when your
classdeffile is not in the path), it will show a notice.So IMHO, you should be both happy and sad: an error would at least give you partial results, on the other hand MATLAB should at least throw a warning that such a thing happened.
With regard to your specific code: I think that
globalvariable is not the best way to go, as a global variables is stored independently from your objects. I’d go with a class variable (i.e.static) if possible. Because now you depend on the global variablenamesin your workspace, which is not saved in the MAT file as far as I know.