Created
September 6, 2017 16:11
-
-
Save ClaytonJY/0bc4a8c9ef3d5d238068315e6cdd786e to your computer and use it in GitHub Desktop.
tryCatch in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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