Matlab:打开和关闭 try/catch 以进行调试

Maz*_*zza 5 debugging matlab if-statement try-catch

我正在使用 try-catch 语句进行类似于以下的冗长计算:

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
Run Code Online (Sandbox Code Playgroud)

当我编写代码时,我不想跳入 catch 语句,因为我喜欢 Matlabsdbstop if error功能。我知道可以使用dbstop if all error以避免在 catch 语句中跳转(我在这里发现:http : //www.mathworks.com/matlabcentral/newsreader/view_thread/102907。)

但问题是 Matlab 有很多内置函数会抛出错误,这些错误会被其他内置函数捕获和处理。我只想止步于我造成的错误。

我的方法是使用一些类似于

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
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为 Matlab 没有看到 try 和 catch 属于彼此。

try/catch调试时有没有更好的方法来处理语句?我一直在评论进出try/catch,但这很烦人而且很麻烦。

Den*_*din 5

您正在寻找的解决方案是dbstop if caught error.

在我发现之前,用try catch块调试代码总是让我发疯。


Dan*_*iel 1

for i=1:1000
    try 
        %do a lot of stuff
    catch me
        if ~debugging
             sendmail('foo@bar.bz', 'Error in Matlab', parse_to_string(me));
        else
             rethrow(me)
        end
    end
end
Run Code Online (Sandbox Code Playgroud)

该代码应该符合您的要求。