Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
R has no try and catch keywords. Try-catch in R is done with functions in base R: tryCatch() runs an expression and, if an error or warning is signaled, transfers control to a handler function you supply; try() is the shorter form that traps errors only. Both ship with R itself, so no package is needed. The key distinction is between handlers that exit the expression (tryCatch()) and handlers that watch and let it continue (withCallingHandlers()), which is covered in the decision table below.
What it is used for in research
Analysis scripts often apply the same step to many inputs: fitting a model to each of many datasets, reading a folder of files, or running thousands of simulation replicates. Without error handling, one failure stops the whole run and discards the work already done. Wrapping the risky step in tryCatch() lets the loop record the failure, return a fallback value such as NA, and move on. This also supports computational reproducibility, because a script that finishes unattended and logs what failed is easier to rerun than one that stops at an unknown point. See also the wider reproducible research practices that scripts like this belong to.
Access: base R, no package
tryCatch(), try(), withCallingHandlers(), stop(), warning() and simpleError() are documented in the base R manual pages for conditions and try (see Sources). R itself is distributed from the Comprehensive R Archive Network at cran.r-project.org. Nothing else has to be installed to use the code on this page.
Step-by-step: wrap an expression in tryCatch()
The usage documented in the R manual is tryCatch(expr, ..., finally). The handlers go in the ... position, named by the class of condition they handle (error, warning, and so on).
- Wrap the risky expression. Put the call in the
exprposition:tryCatch(log(x)). If no condition is signaled,tryCatch()returns the value of the expression, so wrapping changes nothing when all goes well. - Add an error handler. Name the handler
errorand give it a function that takes the condition:tryCatch(log(x), error = function(cnd) NA). Iflog(x)signals an error, the handler’s result, hereNA, becomes the value of the wholetryCatch()call. - Read the condition when you need to. Inside the handler,
conditionMessage(cnd)returns the message andconditionCall(cnd)returns the call that failed. A handler such asfunction(cnd) conditionMessage(cnd)turns the error into a string you can store. - Add a warning handler if warnings should be handled too. Add a second named argument:
tryCatch(expr, error = function(cnd) NA, warning = function(cnd) NA). Several handlers can be supplied in one call. - Add
finallyfor cleanup.finallyis an expression, not a function, evaluated beforetryCatch()returns or exits, whether the expression succeeded or failed. Typical uses are closing a connection or printing a progress line. - Use it inside a loop. A pattern for batch work that keeps going after a failure:
results <- lapply(files, function(f) {
tryCatch(
read.csv(f),
error = function(cnd) {
message("Skipped ", f, ": ", conditionMessage(cnd))
NULL
}
)
})
Each failed file yields NULL and a message; each readable file yields its data frame. The manual’s own example of the same idea uses try() inside lapply() and then keeps the successful results (see the try() section below).
Output and how to read it
What tryCatch() returns
Per the manual, with no condition the value of expr is returned; with a matching handler, the value returned by the handler is returned. The manual’s example tryCatch(stop(e), error = function(e) e, finally = print("Hello")), with e <- simpleError("test error"), returns the error condition object itself and evaluates the finally expression on the way out. A handler that returns the condition is a quick way to inspect what went wrong.
What try() returns
The documented usage is try(expr, silent = FALSE, outFile = getOption("try.outFile", default = stderr())). If there is no error, try() returns the value of the expression. If there is an error, it returns an invisible object inheriting from class "try-error", containing the error message and carrying the condition as its "condition" attribute. By default the message is also printed to stderr; silent = TRUE suppresses that report.
To test for failure, the manual says not to compare class(res) == "try-error" and to use inherits(res, "try-error") instead. The manual’s pattern for keeping only what worked is:
res <- lapply(1:100, function(i) try(doit(x), TRUE))
ok <- res[sapply(res, function(x) !inherits(x, "try-error"))]
The manual also notes that try() is implemented using tryCatch() and that, for programming, something like tryCatch(expr, error = function(e) e) may be more efficient and flexible than try(expr, silent = TRUE).
Exiting handlers or calling handlers: which function to use
This is the distinction that explains most surprises. The R manual describes two mechanisms; Advanced R (Wickham) names them exiting and calling handlers.
| Question | tryCatch() | withCallingHandlers() |
|---|---|---|
| What happens when the condition is signaled? | Control is transferred to the tryCatch() call that established the handler; the expression is abandoned. |
The handler is called in the context where the condition was signaled; if it returns, the next handler is tried and the expression can continue. |
| What does the handler’s return value do? | It becomes the value of the tryCatch() call. |
It is ignored for the result; use it for side effects such as logging. |
| Manual example | tryCatch(stop(e), error = function(e) e, finally = print("Hello")) |
withCallingHandlers({ warning("A"); 1+2 }, warning = function(w) {}) |
In the second example the expression still runs to completion after the warning is signaled, so the block evaluates to 3. With tryCatch() and a warning handler, the same block would stop at the warning and return the handler’s value instead.
Troubleshooting
My warning was not caught
A handler only fires for the classes you name. tryCatch(expr, error = ...) does not handle warnings; add warning = .... Per Advanced R, warnings are by default cached and printed at top level, options(warn = 1) prints them immediately, and options(warn = 2) turns warnings into errors, after which an error handler will catch them.
The wrong handler ran
The manual states that when several handlers are supplied in a single tryCatch() call, the first one is considered more recent than the second. Advanced R adds that the first handler to match any class in the condition’s class vector is called, not the best match. Put the most specific class first.
The result is a try-error that my test missed
Use inherits(res, "try-error"), not class(res) == "try-error"; the manual warns against the comparison because a condition’s class can have length greater than one.
The loop keeps running after the first warning
That is the behavior of withCallingHandlers(), described above. Switch to tryCatch() if you want the warning to end the expression.
Cleanup code runs in the wrong place
The manual states that handlers supplied to the current tryCatch() call are not active when the finally expression is evaluated. An error raised inside finally is therefore not caught by the same call’s handlers.
Free alternatives: the base R condition tools
All of these are part of base R and free to use; the table is limited to what the R manual pages and Advanced R document.
| Function | What it does | Use it when |
|---|---|---|
try(expr, silent = FALSE) |
Traps errors; on error returns an invisible "try-error" object carrying the condition. |
You only need to survive errors and test afterwards with inherits(). |
tryCatch(expr, ..., finally) |
Establishes exiting handlers by condition class, plus a finally expression. |
You want a fallback value, a different action per condition class, or guaranteed cleanup. |
withCallingHandlers(expr, ...) |
Establishes calling handlers that run where the condition was signaled; the expression can continue. | You want to log or record warnings without stopping the computation. |
simpleError(message, call = NULL) with stop() |
Builds an error condition object that stop() can signal. |
You want to test your handlers with a known error. |
For custom condition classes, the base manual page also documents errorCondition(), warningCondition() and messageCondition(), which construct conditions of a particular class with additional fields.
FAQ
Is there a try-catch statement in R?
No keyword exists, but tryCatch() provides the same capability as a function. The expression goes in the first argument and handlers are passed as named arguments.
What is the difference between try() and tryCatch()?
try() traps errors and returns a "try-error" object you test afterwards. tryCatch() lets you choose what to do for each condition class and run a finally expression. The manual notes that try() is implemented using tryCatch().
How do I keep a loop going after an error in R?
Wrap the body in tryCatch() with an error handler that returns a fallback such as NA or NULL, as in the lapply() example above. If the loop also needs to cope with missing values afterwards, see replacing NA with 0 in R.
How do I get the error message?
In the handler, call conditionMessage(cnd); conditionCall(cnd) gives the call that failed.
Does finally run if there is no error?
Yes. The manual describes finally as an expression evaluated before returning or exiting, and its example tryCatch(1, finally = print("Hello")) has no error at all.
Where do I go next for working with R?
Related CASRAI guides cover concatenating values in R and open code for sharing scripts.
Sources (official docs)
- R Core Team, R manual page conditions (
tryCatch,withCallingHandlers,simpleError): stat.ethz.ch/R-manual/R-devel/library/base/html/conditions.html, checked 2026-10-29. - R Core Team, R manual page try: stat.ethz.ch/R-manual/R-devel/library/base/html/try.html, checked 2026-10-29.
- Hadley Wickham, Advanced R, chapter on conditions (exiting versus calling handlers, handler order,
options(warn=)): adv-r.hadley.nz/conditions.html, checked 2026-10-29. - The Comprehensive R Archive Network: cran.r-project.org, checked 2026-10-29.







