Xu Wang
Xu Wang

Reputation: 10587

Have R not exit debugger if error

When I'm in the debugger (from a browser statement for ex.), if I find the code that gives an error, R exits the debugger. But I want to stay in it. How can I do that automatically (e.g. I don't want to manually have to remember to reset option(error) to something when I'm in the debugger.

Upvotes: 13

Views: 999

Answers (2)

user2554330
user2554330

Reputation: 44788

You can use options(error = recover). This will exit the debugging session and immediately offer to enter a new one, with variables as they were at the time of the error.

For example,

options(error = recover)
myfun <- function(x) x + "a" ; debug(myfun) ; myfun(2)

This leads to the following interactive lines:

debugging in: myfun(2)
debug: x + "a"
Browse[2]> n
Error in x + "a" (from #1) : non-numeric argument to binary operator

Enter a frame number, or 0 to exit   

1: myfun(2)

Selection: 1
Browse[3]> ls()
[1] "x"
Browse[3]> print(x)
[1] 2
Browse[3]> 

To make this happen automatically, just put the options(error=recover) call as a default for the session.

Upvotes: 6

Carl Witthoft
Carl Witthoft

Reputation: 21492

Your problem may be due to a misunderstanding about the levels of debug. If, for example, you execute debug(myfunc); myfunc(...) , and myfunc calls some other function, then the called function is not in debug mode. If that function throws an error, R quite properly exits the entire environment. Imagine if it didn't: what would happen during non-debug mode?

One solution is: after entering myfunc in debug mode, and you know what called function throws the error, to execute debug(that_func) so you can follow its error path.

Another workaround is to manually enter the offending function call at the debug prompt (instead of hitting RETURN to have the debugger run the next line of your code). In this way, you'll get the error message back but since it was user-called rather than actually executing a line of the code being debug-run, the debugger will not exit.

Please feel free to comment if this is unclear.

Upvotes: 1

Related Questions