Specifying a callback in Matlab after any runtime error

后端 未结 3 788
悲哀的现实
悲哀的现实 2020-12-10 18:55

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

相关标签:
3条回答
  • 2020-12-10 19:34

    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.

    breakpoints_dialog

    0 讨论(0)
  • 2020-12-10 19:39

    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
    
    0 讨论(0)
  • 2020-12-10 19:47

    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
    
    0 讨论(0)
提交回复
热议问题