# Example using try()
x <- "5"
y <- try(as.integer(x))
if (class(y) == "try-error") {
print("An error occurred during conversion")
} else {
print(paste("The value of x is", y))
}
## [1] "The value of x is 5"
# Example using tryCatch()
z <- "abc"
result <- tryCatch({
y <- as.integer(z)
y + 1
}, error = function(e) {
print("An error occurred:")
print(e)
NA
}, warning = function(w) {
print("A warning occurred:")
print(w)
NA
}, finally = {
print("Finally, cleanup code is executed")
})
## [1] "A warning occurred:"
## <simpleWarning in doTryCatch(return(expr), name, parentenv, handler): NAs introduced by coercion>
## [1] "Finally, cleanup code is executed"
print(result)
## [1] NA