Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

R Error Handling


Share

Handle Errors with tryCatch()

In the Errors chapter, you saw that an error stops the program.

Sometimes you know that something can go wrong, for example when a value comes from a user or a file. With tryCatch(), you can catch the error and decide what happens instead:

Example

tryCatch({
  x <- "5" + 10
  print(x)
}, error = function(e) {
  print("Something went wrong")
})

print("The program continues")
Try it Yourself »

Here is how it works:

  • R tries to run the code inside the first { }.
  • "5" + 10 gives an error, so R jumps to the error part and runs that function instead.
  • The error is caught, so the program does not stop. The last line still runs.

Show the Error Message

The function in the error part gets the error as its argument (here called e).

Use conditionMessage(e) to get the error message as text:

Example

tryCatch({
  "5" + 10
}, error = function(e) {
  print(paste("Error:", conditionMessage(e)))
})
Try it Yourself »

Create Your Own Errors

Use the stop() function to create an error yourself. This is useful when a function gets a value that makes no sense:

Example

check_age <- function(age) {
  if (age < 0) {
    stop("Age cannot be negative")
  }
  paste("Age is", age)
}

check_age(-5)

Result:

Error in check_age(-5) : Age cannot be negative
Try it Yourself »

The error message is the text you wrote in stop(). Now you can catch it with tryCatch():

Example

check_age <- function(age) {
  if (age < 0) {
    stop("Age cannot be negative")
  }
  paste("Age is", age)
}

tryCatch({
  check_age(-5)
}, error = function(e) {
  print(conditionMessage(e))
})
Try it Yourself »


Catch Warnings

tryCatch() can also catch warnings. Add a warning part.

The value that the function returns (here 0) becomes the result of tryCatch():

Example

result <- tryCatch({
  as.numeric("hello")
}, warning = function(w) {
  print("That was not a number")
  0
})

result
Try it Yourself »

finally

The code in the finally part always runs at the end, whether there was an error or not:

Example

tryCatch({
  print("Trying...")
  "5" + 10
}, error = function(e) {
  print("Error caught")
}, finally = {
  print("Done")
})
Try it Yourself »

Real-Life Example

This function turns text into a number. If the text is not a number, it returns NA instead of showing a warning:

Example

to_number <- function(x) {
  tryCatch(as.numeric(x), warning = function(w) NA)
}

to_number("42")
to_number("hello")
Try it Yourself »


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.