Skip to content

Instantly share code, notes, and snippets.

@tjvananne
Created August 6, 2017 18:20
Show Gist options
  • Save tjvananne/65e14a960d7b3092d40c4574554164df to your computer and use it in GitHub Desktop.
Save tjvananne/65e14a960d7b3092d40c4574554164df to your computer and use it in GitHub Desktop.
tryCatch() in R -- the basics 101
#' Most basic form of a TryCatch function in R
#' tryCatch() takes two arguments: "expr" and "finally"
#'
#' "expr" is the expression you want to try. It will run as much
#' as it can until coming across an error. When it hits an error, it
#' will stop processing the code in the expression brackets and move
#' to whatever is inside of the "finally" brackets.
#'
#' Wrap the "expr" and/or "finally" in {brackets} if there are several
#' statements you want to run in each of those arguments.
tryCatch(
expr = {
# we'll always successfully print this if it's first in the expression block...
# regardless of if there is an error present below
print("starting the expression we want to try")
x <- 2
y <- 4
# "z" is not declared in this expression below, so this will
# cause an error here...
# try making it another "x" instead of "z" to test it with
# an entirely successful "expr" code block
bool <- (x + z == y)
# if an error is present above, we won't make it to this print statement
print("we just copmleted the expression we want to try")
},
finally = {
print("now we're in the finally block")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment