R Error Handling
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" + 10gives an error, so R jumps to theerrorpart 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 negativeTry 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 »