R Debugging Exercises: 12 Practice Problems

Twelve practice problems on R debugging: traceback, browser, debug, tryCatch, withCallingHandlers, conditions.

RInteractive R
library(rlang) # All exercises are concept-level; run them in an interactive session.

  

Exercise 1: traceback

Show solution
RInteractive R
# After an error: traceback() # Shows the call stack at the moment of error.

  

Exercise 2: debug a function

Show solution
RInteractive R
f <- function(x) { y <- x + 1; y * 2 } # debug(f); f(5) # steps line by line

  

Exercise 3: debugonce

Show solution
RInteractive R
# debugonce(f); f(5) # debugs only the next call

  

Exercise 4: Insert browser()

Show solution
RInteractive R
f <- function(x) { browser() x + 1 } # f(5)

  

Exercise 5: options error = recover

Show solution
RInteractive R
# options(error = recover) # Subsequent errors give you a stack picker # Reset: options(error = NULL)

  

Exercise 6: tryCatch error

Show solution
RInteractive R
out <- tryCatch(stop("boom"), error = function(e) "handled") out

  

Exercise 7: tryCatch warning

Show solution
RInteractive R
tryCatch(as.numeric("a"), warning = function(w) NA)

  

Exercise 8: withCallingHandlers

Show solution
RInteractive R
withCallingHandlers( warning("careful"), warning = function(w) message("got: ", conditionMessage(w)) )

  

Exercise 9: rlang::abort with class

Show solution
RInteractive R
# rlang::abort("nope", class = "my_error")

  

Exercise 10: stop with structured info

Show solution
RInteractive R
stop(simpleError("custom error"))

  

Exercise 11: trace function for profiling-style insertion

Show solution
RInteractive R
# trace(mean, exit = quote(print("called"))) # mean(1:5) # untrace(mean)

  

Exercise 12: setBreakpoint

Show solution
RInteractive R
# Set: setBreakpoint("myfile.R", line = 10) # Clear: setBreakpoint("myfile.R", line = 10, clear = TRUE)

  

What to do next

  • testthat-Exercises (shipped), catch bugs before they reach prod.

Ready to earn the R Debugging Certificate?

The quiz is concept-based and respects your time: pass it once and your verifiable certificate is yours to share on LinkedIn, your resume, or your portfolio. Take it when you feel comfortable with the material.

Attempt the quiz