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.)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With