Escape from nested try - catch statement

2019-04-29 09:34发布

问题:

I am currently debugging code with nested try-catch statements.

I can easily handle the errors with the dbstop command, but each time I look at the code and want to stop running the program, I have to enter dbquit once for each nesting level.

As this is quite annoying I am looking for a solution to really stop debugging all programs once I am done debugging.

Here is an example of how I call the code:

dbstop if error
dbstop if caught error
mytestmain

And here is an example of what the function could look like (the subfunction may or may not be in a different .m file)

function mytestmain 
try
    mytestsub
catch
end

%% Definition of subfunction
function mytestsub
try
    a=b;%generate an error as b is not defined
catch
end

What have I tried?

  • I tried using a script or a function that calls dbquit twice, however this will only execute dbquit once.
  • I tried using dbquit('all'), but with no effect

Note that I prefer not to remove the try-catch statements in the code.

回答1:

You could call dbclear before using dbquit

dbclear all; dbquit;

Note, however, that this will also clear all breakpoints you set manually, hence, if you use breakpoints in addition, you should rather use

dbclear if error; dbclear if caught error; dbquit;


回答2:

This isn't how it's supposed to work. A single dbquit should get you completely out of the debugger regardless of how deeply nested your try/catch statements are and what breakpoints are still set.

Are you running an old version of Matlab? There's a known bug related to dbstop if caught error in pre-R2009b versions of Matlab that sounds like it could cause this behavior. You could upgrade if you're on an older version.

Regardless of your version, try doing dbstop if all error instead of separate dbstop if error and dbstop if caught error statements and see if the behavior changes.

I would have also guessed maybe you're running multiple functions from within the "K>>" prompt and ending up with nested debugger sessions, but the dbquit('all') you did should have taken care of that case.