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?