0Pricing
R Academy · Lesson

withCallingHandlers() and Restarts

Use withCallingHandlers() for non-local condition handling.

tryCatch vs withCallingHandlers

The key difference: tryCatch() establishes a non-local exit — once a condition is caught, control transfers out of the expression and does not return. withCallingHandlers() keeps the call stack intact and can resume execution after handling.

# tryCatch: execution does NOT continue after warning
tryCatch({
  warning('first')
  cat('This line is never reached\n')
}, warning = function(w) cat('tryCatch caught:', w$message, '\n'))

withCallingHandlers Keeps Execution

With withCallingHandlers(), the handler runs but execution continues after the condition is signaled (unless the handler itself throws an error or invokes a restart). The call stack is not unwound.

withCallingHandlers({
  warning('first warning')
  cat('Execution continues here\n')
  warning('second warning')
  cat('And here too\n')
}, warning = function(w) {
  cat('Handler saw:', w$message, '\n')
  invokeRestart('muffleWarning')
})

All lessons in this course

  1. Errors, Warnings, and Messages in R
  2. tryCatch() for Error Recovery
  3. withCallingHandlers() and Restarts
  4. Writing Robust Functions with stop() and warning()
← Back to R Academy