在Matlab中指定任何运行时错误后的回调函数

4

有没有一种方法可以在Matlab发生错误时指定要运行的代码?我通过谷歌搜索了解到RunTimeErrorFcn和daqcallback,但我认为这些是特定于数据采集工具箱的。我希望能够在遇到错误时运行一些代码,比如访问未分配变量之类的bug。(我使用一个名为PsychToolbox的库来占用GPU,因此我想在返回命令提示符之前清除其屏幕。)


也许可以编写一个修改过的“dbstop”,运行一些代码,然后再分派到内置函数?(感谢尝试使用try/catch的想法,Jonas。) - JmG
3个回答

5

如果你将代码放在 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

5

一个技巧是使用错误断点命令:

dbstop if error

当启用此功能时,MATLAB会在错误点进入调试模式。您可以从主工具栏的Debug菜单中访问相同的功能。

breakpoints_dialog


0

如果有人使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接