Debugging back to original error with conditional exception handling, i.e. rethrow

debugging, error-handling, matlab

Solution

I would guess that you cannot do this. As soon as execution enters the `catch` statement, `dbstack` will have to refer to that location inside the catch, so the information necessary to debug at the cause of the error is lost. `ME.stack` will tell you where the exception came from, but that isn't sufficient to debug at that location.

So I doubt you can solve the problem by doing something clever inside the catch. Looking at the documentation for catch, there also doesn't seem to be a way to do a java-style `catch (ExceptionType ME)`.

There might be some hacky ways to solve this by using debug commands programmatically. For example, `S = dbstatus` saves the debug state and if there was a way to resume from a saved state, then you could attach this to the exception. But I can't find any documented way to do that.

Problem

In Matlab, there is, as far as I know, no good way to conditionally catch exceptions (correct me if I'm wrong). The only way is to catch the exception, check the identifier, and rethrow the error if this particular error can not be handled. That's acceptable though inconvenient. However, when I use Matlabs `dbstop if error`, I end up at the `ME.rethrow()` line. I'm then unable to `dbup` back to the place where the original error was caused. ``` function test_excc try sub_test() catch ME if strcmp(ME.identifier, 'test:notsobad') fprintf(1, 'Fine\n'); else ME.rethrow(); end end end function sub_test sub_sub_test(); end function sub_sub_test() if rand>0.5 error('test:error', 'Noooo!'); else error('test:notsobad', 'That''OK'); end end ``` Example usage: ``` >> test_excc() Error using test_excc>sub_sub_test (line 21) Noooo! Error in test_excc>sub_test (line 16) sub_sub_test(); Error in test_excc (line 4) sub_test() 9 ME.rethrow(); K>> dbstack > In test_excc at 9 ``` Although the Matlab desktop environment prints the entire stack trace back to `sub_sub_test`, the debugger does not give me the possibility to go up the stack trace and debug inside this function. I am aware of `dbstop if caught error`. However, this will debug into any caught error, which may be many if software makes heavy use of exceptions. I only want to stop on uncaught errors, but I want to stop where the error is generated — not where it's rethrown. My question: - In Matlab, how do I conditionally catch an error (based on error identifier) and debug into the place where the error is originally thrown?

Original source