Error handling helps your program keep running even when something goes wrong. tryCatch lets you catch errors and decide what to do next.
0
0
Error handling (tryCatch) in R Programming
Introduction
When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When calling a function that might fail with bad input.
When connecting to a database that might be offline.
Syntax
R Programming
tryCatch(
expr,
error = function(e) {
# code to run if error happens
},
warning = function(w) {
# code to run if warning happens
},
finally = {
# code to run at the end no matter what
}
)expr is the code you want to try running.
You can handle error, warning, and finally blocks separately.
Examples
This tries to take the log of -1, which causes a warning. The warning handler runs and prints a message.
R Programming
tryCatch( log(-1), error = function(e) { print("Error caught!") }, warning = function(w) { print("Warning caught!") } )
This code forces an error with
stop(). The error handler catches it and prints the message.R Programming
tryCatch( stop("This is an error"), error = function(e) { print(paste("Caught error:", e$message)) } )
Sample Program
This program defines a function to divide two numbers safely. If dividing by zero happens, it catches the error and prints a message. It always prints a final message after trying.
R Programming
safe_divide <- function(a, b) {
tryCatch(
{
if (b == 0) stop("Cannot divide by zero")
result <- a / b
print(paste("Result is", result))
},
error = function(e) {
print("Error: Cannot divide by zero.")
},
finally = {
print("Division attempt finished.")
}
)
}
safe_divide(10, 2)
safe_divide(5, 0)OutputSuccess
Important Notes
Use tryCatch to keep your program from stopping unexpectedly.
The finally block runs no matter what, good for cleanup.
You can handle warnings separately if you want to respond to them.
Summary
tryCatch helps you catch errors and warnings in R.
It keeps your program running smoothly even when problems happen.
You can customize what happens on error, warning, or always at the end.