Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: Turning try/catch on and off for debugging

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('[email protected]', '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('[email protected]', '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.

like image 838
Mazza Avatar asked Dec 09 '13 20:12

Mazza


People also ask

How do I stop errors in Matlab?

You can use a try/catch statement to execute code after your program encounters an error. try/catch statements can be useful if you: Want to finish the program in another way that avoids errors.


2 Answers

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.

like image 80
Dennis Jaheruddin Avatar answered Nov 08 '22 05:11

Dennis Jaheruddin


for i=1:1000
    try 
        %do a lot of stuff
    catch me
        if ~debugging
             sendmail('[email protected]', 'Error in Matlab', parse_to_string(me));
        else
             rethrow(me)
        end
    end
end

This code should match your requirements.

like image 42
Daniel Avatar answered Nov 08 '22 06:11

Daniel