Is there a way to specify code to be run whenever an error occurs in Matlab? Googling I came across RunTimeErrorFcn and daqcallback, but I believe these are specific to the Data Acquisition Toolbox. I want something for when I just trip over a bug, like an access to an unassigned variable. (I use a library called PsychToolbox that takes over the GPU, so I want to be able to clear its screen before returning to the command prompt.)
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If you wrap your code in TRY/CATCH blocks, you can execute code if an error occurs, which can be customized depending on the specific error using the MEXCEPTION object.
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
回答2:
One trick is to use Error Breakpoints by issuing the command:
dbstop if error
which when enabled, causes MATLAB to enter debug mode at the point of error. You can access the same functionality from the Debug
menu on the main toolbar.
回答3:
If somebody uses GUI and wants to have a "global" error detection, than solution might look something like this...
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