Error Handling (tryCatch)
Error handling is how you signal problems with stop(), warning(), and message(), and how you catch them with tryCatch() so a failure produces a graceful fallback instead of crashing your program.
Learn Error Handling (tryCatch) in our free R course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free R course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
You'll learn to raise the three R conditions, catch them with tryCatch error/warning/finally handlers, read the message with conditionMessage(), use the lightweight try(), and validate inputs early with stopifnot().
What You'll Learn in This Lesson
1️⃣ Signalling: stop, warning, message
R has three condition types you can raise yourself. stop() is a fatal error that halts execution. warning() flags something suspicious but lets the code continue. message() prints an informational note. Choosing the right one makes your functions communicate clearly.
2️⃣ Catching with tryCatch()
tryCatch() runs an expression and, if a condition fires, hands it to the matching handler — error = , warning = , or message = — each a function receiving the condition object. conditionMessage() extracts its human-readable text. The handler's return value becomes the result.
3️⃣ The finally Block
A finally = block runs after the expression and any handler, whether the call succeeded or failed. It's where you put guaranteed cleanup — closing a file, releasing a connection, or simply logging that an attempt finished.
4️⃣ try() and stopifnot()
try() is the lightweight option: it prints an error but lets your script keep going, returning a "try-error" object you can test. stopifnot() is a one-line input guard — it errors unless every condition is TRUE , naming the one that failed.
Your turn. Fill in the ___ blank, run it, and compare with the expected output.
This ties everything together: validate with stopifnot() , raise your own stop() , catch it with tryCatch() , and clean up with finally — the shape of every robust function.
📋 Quick Reference — Error Handling
Practice quiz
Which function raises a fatal ERROR that halts execution?
- message()
- stop()
- warning()
- cat()
Answer: stop(). stop() signals an error and aborts the call unless it is caught.
Which function signals a problem but lets execution CONTINUE?
- warning()
- stop()
- abort()
- halt()
Answer: warning(). warning() flags something suspicious but does not stop the code.
Which function prints an informational note to the console (stderr)?
- stop()
- warning()
- print()
- message()
Answer: message(). message() emits an informational note without implying an error.
What does tryCatch() do when a matching condition fires?
- Ignores it silently
- Runs the matching handler and returns its value
- Restarts R
- Prints the call stack and quits
Answer: Runs the matching handler and returns its value. tryCatch() stops evaluating the expression and runs the matching handler, returning what it returns.
Which tryCatch() argument always runs, whether or not an error occurred?
- always =
- ensure =
- finally =
- cleanup =
Answer: finally =. finally = runs at the end no matter what, ideal for cleanup.
Which function extracts the human-readable text from a condition object e?
- conditionMessage(e)
- message(e)
- errorText(e)
- e$text
Answer: conditionMessage(e). conditionMessage(e) returns the condition's message string.
What does try() return when its expression errors?
- NULL
- A warning object
- An object of class "try-error"
- The number 0
Answer: An object of class "try-error". try() prints the error but returns a "try-error" object so the script continues.
What does stopifnot(is.numeric(x), length(x) > 0) do?
- Always returns TRUE
- Prints x
- Loops over x
- Errors unless every condition is TRUE
Answer: Errors unless every condition is TRUE. stopifnot() throws an informative error the moment any condition is not entirely TRUE.
In tryCatch(), how is an error handler specified?
- error = function(e) { ... }
- onError: { ... }
- catch(e) { ... }
- except e: ...
Answer: error = function(e) { ... }. Handlers are named arguments like error = function(e) ... and warning = function(w) ...
In tryCatch(), what becomes the overall result when a handler runs?
- Always NA
- Always NULL
- The handler's return value
- The original error object
Answer: The handler's return value. The matching handler's return value becomes the result of the tryCatch() call.