Skip to content

Instantly share code, notes, and snippets.

@ClaytonJY
Created September 6, 2017 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ClaytonJY/0bc4a8c9ef3d5d238068315e6cdd786e to your computer and use it in GitHub Desktop.
Save ClaytonJY/0bc4a8c9ef3d5d238068315e6cdd786e to your computer and use it in GitHub Desktop.
tryCatch in R
# test function
f <- function(x) {
if (missing(x)) {
stop("error, Will Robinson")
} else {
x
}
}
f(1) # 1
f() # error
g <- function(x) {
tryCatch(
f(x),
error = function(c) { # need to accept the condition even if we don't use it
return("There was an error!")
}
)
}
g(1) # 1
g() # error message caught, output is string returned by our error handler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment