I've recently started using browser()
in function definitions for debugging (a great tool!). I feel like print()
debugging has been slowing my learning curve of built-in debugging tools. What are some others I've been missing?
views:
386answers:
4I'd say that debugging is an art form, so there's no clear silver bullet. There are good strategies for debugging in any language, and they apply here too (e.g. read this nice article from IBM). For instance, the first thing is to reproduce the problem...if you can't do that, then you need to get more information (e.g. with logging). Once you can reproduce it, you need to reduce it down to the source.
Rather than a "trick", I would say that I have a favorite debugging routine:
- When an error occurs, the first thing that I usually do is look at the stack trace by calling
traceback()
: that shows you where the error occurred, which is especially useful if you have several nested functions. - Next I will set
options(error=recover)
; this immediately switches into browser mode where the error occurs, so you can browse the workspace from there. - If I still don't have enough information, I usually use the
debug()
function and step through the script line by line.
The best new trick in R 2.10 (when working with script files) is to use the findLineNum()
and setBreakpoint()
functions.
As a final comment: depending upon the error, it is also very helpful to set try()
or tryCatch()
statements around external function calls (especially when dealing with S4 classes). That will sometimes provide even more information, and it also gives you more control over how errors are handled at run time.
These related questions have a lot of suggestions:
The edit()
and fix()
functions can also be quite helpful.
I also use the function "mtrace" (and then mtrace.off()) on a function (from the "debug" package), which is amazingly useful.
After going through all the steps suggested here I just learned that setting .verbose = TRUE
in foreach()
also gives me tons of useful information. In particular foreach(.verbose=TRUE)
shows exactly where an error occurs inside the foreach loop, while traceback()
does not look inside the foreach loop.