我有一個Matlab類,實現序列化和反序列化會很痛苦,而且不需要。 因此,我已經超負荷saveobj
如下:防止序列化
function sobj = saveobj(self)
sojb = [];
error(['atmlab:' mfilename ':nostoring'], ...
['You tried to store %s %s. Loading is impossible, ' ...
'therefore I refuse to store. Sorry.'], ...
class(self), self.name);
end
不幸的是,當我測試,Matlab的嘗試是有益的,變成警告到錯誤(兩次出於某種原因):
>> save('/tmp/test.mat', 'X')
Warning: While saving an object of class 'SatDataset':
You tried to store SatDataset amsua. Loading is impossible, therefore I refuse to store. Sorry.
(Type "warning off atmlab:SatDataset:nostoring" to suppress this warning.)
Warning: While saving an object of class 'SatDataset':
You tried to store SatDataset amsua. Loading is impossible, therefore I refuse to store. Sorry.
(Type "warning off atmlab:SatDataset:nostoring" to suppress this warning.)
我可以使用undocumented feature打開警告插入錯誤:
>> warning error atmlab:SatDataset:nostoring
>> save('/tmp/test.mat', 'X')
Error using save
While saving an object of class 'SatDataset':
You tried to store SatDataset amsua. Loading is impossible, therefore I refuse to store. Sorry.
Unexpected error status flag encountered. Resetting to proper state.
但是,這並不理想,因爲我不想要依靠UNDOC並且我肯定不想強迫用戶這樣做。
我該如何有效地拋出一個錯誤,防止用戶嘗試從我的班級串行化對象?
按要求,最低例子重現情況:
% in TestClass.m
classdef TestClass < handle
methods
function sobj = saveobj(self)
sojb = [];
error('Unable to store %s objects', class(self));
end
end
end
% on the interactive prompt:
>> t = TestClass();
>> save('/tmp/fubar.mat', 't');
Warning: While saving an object of class 'TestClass':
Unable to store TestClass objects
Warning: While saving an object of class 'TestClass':
Unable to store TestClass objects
不。我的代碼不會拋出錯誤,即使我調用'error',我的代碼也會拋出警告。 – gerrit 2013-03-18 12:30:10
並且將呼叫更改爲警告並不能解決問題嗎? – 2013-03-18 17:08:57
問題是我不能拋出錯誤,因爲Matlab會將錯誤更改爲警告。將其更改爲警告並不能解決無法拋出錯誤的問題。 – gerrit 2013-03-18 18:19:00