HOWTO · R
How to Use the tryCatch Function for Condition Handling in R
Learn how tryCatch handles errors, warnings, and messages in R, how its handlers return values, and how finally supports cleanup.
On this page
Use tryCatch() in R when an expression may signal a condition and your code needs a defined response. An exiting handler can turn an error into a fallback value, while finally can release a resource after either success or failure. The key is to match each handler to the condition you want to handle and remember that a handler’s return value becomes the result of tryCatch().
How tryCatch() handles conditions in R
R conditions communicate events. stop() signals an error, warning() signals a warning, and message() signals an informational message. tryCatch() evaluates an expression and looks for handlers named for the condition classes it should handle, such as error, warning, or message. Its general form is tryCatch(expression, error = function(e) ..., finally = {...}); the handlers and finally argument are optional. Handlers receive a condition object, and conditionMessage(e) retrieves its message. These handlers are exiting handlers: when one handles a condition, evaluation leaves the protected expression and the handler’s value becomes the call’s result. A warning handler therefore also prevents the rest of that expression from running. finally is different: it runs after the expression or a handler finishes, and its value does not replace the result.
Handle errors with tryCatch()
Put the operation that may fail in the first argument and return a useful fallback from the error handler. Division by zero is not a suitable demonstration of an R error: ordinary numeric division returns Inf. Passing text to log(), by contrast, signals an error.
Run this example:
cat(sum(c(2, 3)), "\n", sep = "")
safeLog <- function(x) {
tryCatch(
log(x),
error = function(e) paste("Could not calculate log:", conditionMessage(e))
)
}
answer <- safeLog("not a number")
cat(answer, "\n", sep = "")
The protected expression stops at the error, so any statements after log(x) inside that expression would not run. The handler returns a character value, which becomes answer. Code after the tryCatch() call can continue and use that result. Choose a fallback that callers can distinguish from an ordinary successful value, such as a structured result or a clearly documented sentinel.
Handle warnings and messages
Warnings and messages are conditions too, but they have different purposes. A warning signals that a result may need attention; a message provides information. An exiting handler for either type ends evaluation of the protected expression at that point. If your goal is only to record a warning and then continue the calculation, use withCallingHandlers() instead; its calling handler can observe the condition while the original expression continues.
This example handles both condition types and returns the handler’s value:
conditionResult <- function() {
tryCatch(
{
warning("using an approximate value")
message("calculation complete")
42
},
warning = function(w) paste("Handled warning:", conditionMessage(w)),
message = function(m) paste("Handled message:", conditionMessage(m))
)
}
cat(conditionResult(), "\n", sep = "")
Here the warning handler is selected first, so the message and value expression are not reached. To handle a condition without exiting, use withCallingHandlers(); its calling handler can observe the condition while the protected expression continues. To suppress a warning or message, invoke its restart from that handler with invokeRestart("muffleWarning") or invokeRestart("muffleMessage"), respectively. By contrast, an exiting handler in tryCatch() leaves the protected expression and returns the handler’s value. Do not assume that adding a handler merely logs a condition and lets the protected expression finish.
Use finally for cleanup
Use finally for work that must happen after the attempt, whether it succeeds or signals a handled condition. A cleanup action should also be safe if setup fails partway through. For a connection, initialize its variable before the attempt and close it only if it was opened:
path <- tempfile()
writeLines("first line", path)
con <- NULL
contents <- tryCatch(
{
con <- file(path, open = "r")
readLines(con)
},
error = function(e) paste("Read failed:", conditionMessage(e)),
finally = {
if (!is.null(con) && isOpen(con)) close(con)
unlink(path)
}
)
print(contents)
The connection is closed before the temporary file is removed, and unlink() is safe if an earlier operation failed. In application code, keep cleanup focused on releasing resources; avoid returning the useful result from finally, because that value is ignored.
Test and troubleshoot condition handling
When a handler appears not to run, check the condition’s type and where it is signaled. tryCatch(error = ...) handles errors, not every warning or message. Use stop() to create an error deliberately; a calculation that yields Inf may be valid R behavior rather than a failure. During diagnosis, inspect conditionMessage(e) and, if useful, class(e) so you can decide whether the handler is too broad or too narrow.
If code after a warning or message never runs, an exiting handler likely handled that condition. Use withCallingHandlers() when the expression should continue after observing a warning or message. If a cleanup step is skipped, place it in finally and make it tolerate partially initialized resources. Test the success and failure paths separately, and have handlers return values with a documented type so downstream code can respond consistently. tryCatch() works around any R expression that can signal a condition; it does not make a failed operation succeed, so preserve enough context in the fallback or log for the caller to decide what to do next.