6.10 Conditions, Errors, and Unwinding

R RUNTIMESTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18
Before this page How R Executes Code, Environments

6.10.1 Motivation

R code does not always run to completion. stop() raises an error, warning() and message() raise milder conditions, and packages define their own classes. For each one the runtime has to find a handler, run the cleanup code of every function call it abandons, and then either resume or return to the top level. That machinery is the condition system.

In multithreaded R, conditions become a synchronization point. A worker that encounters an error must notify the main thread. The main thread must decide: restart, abort, or ask the user. A worker cannot just print a message and stop.

6.10.2 Mental model

Conditions, handlers, and restarts

R’s condition system has three layers. A condition is an object that signals something: an error, a warning, a message. A handler is a function that responds to a condition. A restart is a labeled point in the code where execution can resume with a chosen value.

When code encounters a problem, it signals a condition. The runtime walks the handler stack, looking for a handler whose class matches one of the condition’s classes. There are two kinds. A calling handler, set up by withCallingHandlers(), runs on top of the code that signaled, without unwinding anything; if it returns, it has declined, and the search goes on. An exiting handler, set up by tryCatch(), ends the search: R unwinds the stack back to the tryCatch() call and runs the handler there.

If no handler takes an error, R’s default handling prints the message and jumps back to the top level, which is the prompt in an interactive session. On the way it abandons every function call between the error and the top level, popping their C stack frames and discarding their contexts. Leaving calls this way is unwinding.

The call stack and contexts

When R evaluates a closure call, it creates a context: an RCNTXT struct on the C stack that records the call, the function’s environment, the promises for its arguments, its on.exit code, the handler stack as it was on entry, and a jump buffer that an error can longjmp to. Each context points to the one below it, and the global R_GlobalContext points to the newest.

During unwinding R walks from the newest context down to the target, and for each function context with on.exit() code it runs that code before discarding the context.

f <- function() {
  on.exit(print("cleaning up"))
  stop("error")
}
f()
# Error in f() : error
# [1] "cleaning up"

R prints the error message first and runs the cleanup afterwards. The default error handler (verrorcall_dflt in errors.c) writes the message to stderr and then jumps to the top level, and that jump is what runs the on.exit code. Under tryCatch() the order is reversed: the stack unwinds to the tryCatch() call, running the cleanup, and only then does the handler run.

Handlers and the handler stack

The handler stack is separate from the call stack. When a tryCatch() block is entered, a handler is pushed onto the handler stack. When the block exits, the handler is popped. Each context saves the handler stack on entry, so leaving a frame by any route, unwinding included, restores it.

tryCatch(
  { stop("error") },
  error = function(e) { print("caught") }
)

The error handler is pushed when tryCatch() begins. When stop("error") is called, the runtime walks the handler stack and finds the error handler. Because it is an exiting handler, R unwinds to the tryCatch() frame and then calls the handler with the condition object. The handler’s return value, here the value of print("caught"), becomes the value of tryCatch(). If the handler itself calls stop(), that is a new error, signaled from inside tryCatch() after its own handler has been popped.

6.10.3 Mechanism

Signaling a condition

When user code calls stop("boom"), R walks the handler stack with the message. A handler receives a condition object of class c("simpleError", "error", "condition"). For a plain message, R builds that object only when a handler needs one (vsignalError in errors.c).

If a handler matches the condition class, the handler function is called with the condition object. It can inspect the message and the call that raised it, and decide to handle the condition or signal another.

Unwinding

Unwinding is a controlled panic. R picks a target context, and longjmps toward it. If a function context on the way has on.exit() code, the jump stops there first: R discards the C frames above that context, runs its on.exit() code, and jumps on, so the stack unwinds in stages, newest context first (R_jumpctxt in context.c).

on.exit() code is stored in the context. A second on.exit() call replaces the first unless it passes add = TRUE, which appends; add = TRUE, after = FALSE puts the new expression in front. The expressions run in list order.

f <- function() {
  on.exit(stop("cleanup error"))
  stop("original error")
}
f()
# Error in f() : original error
# Error in f() : cleanup error

Both are reported, in that order. R has already printed the original error when it starts unwinding. The on.exit expression then raises a second error, which is printed in turn and starts a jump of its own. Any further on.exit expressions of the same function still run, because R takes each one off the list before evaluating it. A failing cleanup adds a second message, and the first one stays visible.

An interactive session survives an uncaught error: unwinding ends at the top-level context and R returns to the prompt. Rscript is not interactive, and there R stops with “Execution halted” once the error reaches the top level.

Execution frames and C boundaries

R code runs inside C functions. When R evaluates a function call, the evaluator calls a C function that implements it, and that C function can call back into R, so the C stack interleaves C frames and evaluator frames.

An R error does not return through those C frames. The jump goes from the point of the error toward the target context’s jump buffer, stopping at any function context on the way that has on.exit() code, and every C frame it passes over is abandoned: no return statement runs, and no error flag is checked on the way. R restores its own state from the target context, including the protect stack height and the R_alloc stack, and the garbage collector reclaims R objects. Nothing frees memory a C function got from malloc, releases a lock it held, or runs a C++ destructor it relied on.

C code that has to clean up uses R_UnwindProtect(), documented since R 3.5.0. It calls a function, and if an error or any other jump passes through, it calls a cleanup function and then resumes the jump with R_ContinueUnwind(). R_tryCatchError() and R_ToplevelExec() stop the jump instead. C++ code needs this to run destructors: cpp11, for example, wraps R API calls so that an R error becomes a C++ exception.

6.10.4 Internal mechanics

Condition objects

A condition in GNU R is an S3 object: a list with a class attribute. A simpleError has two fields, message and call.

tryCatch(
  stop("boom"),
  error = function(e) {
    print(class(e))           # "simpleError" "error" "condition"
    print(conditionMessage(e)) # "boom"
  }
)

The condition object is created by the signaling function (stop, warning, message). The runtime passes it to matching handlers.

Handler registration

Handlers are registered via tryCatch(), withCallingHandlers(), or lower-level functions. Each entry on the handler stack is tagged with one condition class, so tryCatch() with both error = and warning = pushes two entries.

When a condition is signaled, the runtime walks the handler stack and tests each entry’s class against the condition’s classes. The most recently established match goes first. A calling handler that returns has declined, and the walk continues below it. An exiting handler ends the walk.

If no handler takes the condition, R uses its default: an error is printed and unwinds to the top level, a warning is saved and printed later, a message is printed to stderr.

Cleanup and finalization

on.exit() code runs when a function call exits, whether by normal return or by unwinding. That makes it the place for releasing resources: closing connections, restoring options, removing temporary files.

f <- function(filename) {
  h <- file(filename, "r")
  on.exit(close(h))
  # ... use h ...
}

The file is closed even if the code inside f raises an error, though not if the session ends through quit().

6.10.5 Concurrency implications

In multithreaded R, condition handling becomes more complex.

A worker thread has its own call stack and context list. An error in the worker searches the worker’s handler stack and unwinds the worker’s contexts, and nothing else.

The main thread learns of the error only if the worker reports it. This is a design choice: the apartment model keeps workers isolated, so each worker’s failure is local.

Condition signals are thread-local in the apartment model. An error in a worker does not unwind the main thread’s stack.

To get an error to the main thread, the worker has to send it. The usual pattern is the one parallel’s socket workers already use: evaluate each task inside tryCatch() and send the error back as a value. The worker loop in parallel returns the message as a "try-error" object (worker.R), and the main side raises it with checkForRemoteErrors().

6.10.6 Conditions in GNU R

GNU R implements all of this with a context stack (linked C structs), a handler stack, and setjmp/longjmp for non-local exits.

The context stack is global. There is one stack per R process. When an error unwinds, the contexts above the target are discarded: all of them for an uncaught error, those above the tryCatch() frame for a caught one.

The handler stack is a pairlist held in a C global, R_HandlerStack, not a variable in any R environment. New handlers are consed onto its front, and the search walks it from the front.

on.exit code is stored in its function’s context and runs when unwinding passes that context.

GNU R keeps one context stack per process, headed by the C global R_GlobalContext. Errors, restarts and the other non-local exits all leave through one function, R_jumpctxt in context.c.

6.10.7 Conditions in threaded-r

threaded-r makes the context stack per-thread. R_GlobalContext, R_ToplevelContext, R_HandlerStack and R_RestartStack move into per-thread state together, because the jump code saves and restores them as a set. An error in one interpreter searches only that interpreter’s handlers and unwinds only its stack. In makeCluster(type = "THREAD"), a task’s error comes back through the same worker loop and checkForRemoteErrors() as from a PSOCK worker, and the cluster stays usable afterwards.

Expressions registered with on.exit() run as usual during unwinding. They clean up local resources (files, memory) owned by the interpreter.

threaded-r isolates condition handling per-interpreter. An error in one interpreter unwinds only that interpreter’s stack.

6.10.8 Conditions in r-in-rust

rrs’s evaluator returns Result<Handle, Signal>, where Signal covers errors and other conditions that unwind, return(), break, next and restarts (crates/rrs-eval/src/lib.rs). Unwinding through the evaluator is ordinary Rust control flow: each frame passes the Signal up with the ? operator or matches on it.

R code still gets R’s semantics. tryCatch() and on.exit() are implemented as places that inspect the Signal on its way up, not as jump targets. A withCallingHandlers() handler runs at the point of the signal, before anything unwinds, as in GNU R (crates/rrs-eval/src/conditions.rs).

6.10.9 The hard part

Conditions are a flexible tool for error handling. They make it easy to recover from errors without restructuring code, and the flexibility has costs.

Cleanup code runs in the middle of an unwind. A failing on.exit expression does not stop the unwind, as the example above shows, but it starts a second error from inside the first, and in a multithreaded runtime both have to stay inside the interpreter that raised them.

Conditions are also dynamically scoped. A handler registered in one function can catch conditions raised in a function it calls, nested arbitrarily deep. This makes it hard to reason about where a condition will be handled. In multithreaded code, this non-local control flow is a hazard.

6.10.10 Open questions

Must a worker thread that encounters an unhandled condition automatically notify the main thread? Must the notification block the worker until the main thread responds?

If a worker is interrupted (sent a signal), what state must be preserved? Must the worker unwind normally, or must it exit abruptly?

Further reading

R Language Definition, Chapter 8, “Exception handling”: https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Exception-handling

R Internals, Section 1.4, “Contexts”: https://cran.r-project.org/doc/manuals/r-release/R-ints.html#Contexts

Writing R Extensions, Section 6.13, “Condition handling and cleanup code”, on R_UnwindProtect: https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Condition-handling-and-cleanup-code

Hadley Wickham, Advanced R, Chapter 8, “Conditions”: https://adv-r.hadley.nz/conditions.html

Where this appears

  • threaded-r Workers must preserve the handler stack and execution frames. An error in a worker affects only that worker.
  • r-in-rust (rrs) The evaluator carries conditions as a Rust Result value, so unwinding through it is ordinary Rust control flow, not a longjmp.

Where to go next

Back to top