Generating Error & Error Handling in R

beera <- function(expr){
tryCatch(expr,
error = function(e){
message("An error occurred:\n", e)
},
warning = function(w){
message("A warning occured:\n", w)
},
finally = {
message("Finally done!")
})
}
beera({
2 + 2
})
Finally done!
[1] 4
beera({
"two" + 2
})
An error occurred:
Error in "two" + 2: non-numeric argument to binary operator
Finally done!
beera({
as.numeric(c(1, "two", 3))
})
A warning occured:
simpleWarning in doTryCatch(return(expr), name, parentenv, handler): NAs introduced by coercion
Finally done!
stop("Something erroneous has occurred!")Error: Something erroneous has occurred!
error_if_n_is_greater_than_zero <- function(n){
stopifnot(n <= 0)
n
}

error_if_n_is_greater_than_zero(5)
Error in error_if_n_is_greater_than_zero(5): n <= 0 is not TRUE
warning("Consider yourself warned!")
Warning: Consider yourself warned!
message("In a bottle.")
In a bottle.

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Angela W.

Angela W.

Data science professional. Love food and obsessed with efficiency.