Matlab: Turning try/catch on and off for debugging

debugging, if-statement, matlab, try-catch

Solution

The solution that you are looking for is `dbstop if caught error`.

Before I found that, debugging code with `try catch` blocks always drove me crazy.

Problem

I am using a try-catch statement for a lengthy calcuation similar to the following: ``` for i=1:1000 try %do a lot of stuff catch me sendmail('foo@bar.bz', 'Error in Matlab', parse_to_string(me)); end end ``` When I am writing on my code I do not want to jump in the catch statement because I like Matlabs `dbstop if error` feature. I know it is possible to use `dbstop if all error` in order to avoid jumping in the catch statement (I found that here: http://www.mathworks.com/matlabcentral/newsreader/view_thread/102907 .) But the problem is that Matlab has a lot of inbuilt functions which throw errors which are caught and handled by other inbuilt functions. I only want to stop at errors caused by me. My approach would be to use some statement similar to ``` global debugging; % set from outside my function as global variable for i=1:1000 if ~debugging try end %do a lot of stuff if ~debugging catch me sendmail('foo@bar.bz', 'Error in Matlab', parse_to_string(me)); end end end ``` This does not work because Matlab doesn't see that try and catch belong to each other. Are there any better approaches to handle `try/catch` statements when debugging? I have been commenting in and out the `try/catch`, but that is pretty annoying and cumbersome.

Original source