Skip to content

Instantly share code, notes, and snippets.

@pr130
Created July 2, 2018 21:08
Show Gist options
  • Save pr130/bb7a036b3652db755bc191e52f194713 to your computer and use it in GitHub Desktop.
Save pr130/bb7a036b3652db755bc191e52f194713 to your computer and use it in GitHub Desktop.
Trying to exit a cascade of functions in R
# nested error handling
third_level <- function(c, d){
print(paste0("c ", c, " d ", d))
if (c > 2){
stop("Invalid value for c. Exiting third level.")
}
else {
return(c + d)
}
}
second_level <- function(a, b){
print(paste0("a ", a, " b ", b))
if(a > 3){
tryCatch(
expr = {
return(third_level(a, b))
},
error = function(e) {
print(paste0("catched the error from third level", e))
stop("Exiting second level")
}
)
} else {
stop("Invalid value for a. Exiting second level")
}
}
top_level <- function(x, y){
print(paste0("x ", x, " y ", y))
if (x > 5){
stop("Invalid value for x. exiting top level directly.")
} else {
tryCatch(
expr = {
return(second_level(x, y))
},
error = function(e) {
print(paste0("catched the error ", e))
stop("Exiting top level")
}
)
}
}
# error at top level
top_level(6, 1)
# error at second level
top_level(2, 2)
# error at third level
top_level(4, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment