有没有一种方法可以在Matlab发生错误时指定要运行的代码?我通过谷歌搜索了解到RunTimeErrorFcn和daqcallback,但我认为这些是特定于数据采集工具箱的。我希望能够在遇到错误时运行一些代码,比如访问未分配变量之类的bug。(我使用一个名为PsychToolbox的库来占用GPU,因此我想在返回命令提示符之前清除其屏幕。)
有没有一种方法可以在Matlab发生错误时指定要运行的代码?我通过谷歌搜索了解到RunTimeErrorFcn和daqcallback,但我认为这些是特定于数据采集工具箱的。我希望能够在遇到错误时运行一些代码,比如访问未分配变量之类的bug。(我使用一个名为PsychToolbox的库来占用GPU,因此我想在返回命令提示符之前清除其屏幕。)
如果你将代码放在 TRY/CATCH 块中,当出现错误时,可以执行自定义的代码,使用 MEXCEPTION 对象可以根据特定的错误进行定制。
try
% do something here
catch me
% execute code depending on the identifier of the error
switch me.identifier
case 'something'
% run code specifically for the error with identifier 'something'
otherwise
% display the unhandled errors; you could also report the stack in me.stack
disp(me.message)
end % switch
end % try/catch
如果有人使用GUI并希望拥有“全局”的错误检测,则解决方案可能会像这样...
function varargout = Program(varargin)
try
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @program_OpeningFcn, ...
'gui_OutputFcn', @program_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
catch exception
beep
h = errordlg('Unexpected error, the program will be restarted.','Syntax
error','modal');
uiwait(h)
Program
end