Home > Software design >  `tryCatch` with variable assignment
`tryCatch` with variable assignment

Time:06-16

I'm trying to run a function but get some knowledge of whether or not it completed successfully, issued an error or a warning, I've tried doing the following:

ret <- 0 

tryCatch(expr = {
  cat(non_existing_variable, "\n")
  },
  error = function(e) {
    ret <- 1
    cat("Got into error condition!\n")
  },
  warning = function(w) {
    ret <- 2
    cat("Got into warning condition!\n")
  }
)

cat("ret =", ret, "\n")

But it prints:

Got into error condition!
ret = 0 

I expected it to yield ret = 1.

What is happening here?

CodePudding user response:

The ret variable is being assigned in a different scope inside tryCatch. You could use the <<- operator for assignment here if you want ret to be assigned in the parent frame:

ret <- 0 

tryCatch(expr = {
  cat(non_existing_variable, "\n")
  },
  error = function(e) {
    ret <<- 1
    cat("Got into error condition!\n")
  },
  warning = function(w) {
    ret <<- 2
    cat("Got into warning condition!\n")
  }
)
#> Got into error condition!

cat("ret =", ret, "\n")
#> ret = 1

However, an even better way to do this to avoid unexpected assignments in the calling frame would be to get the caught error to explicitly return:

ret <- tryCatch(expr = {
  cat(non_existing_variable, "\n")
  return(0)
  },
  error = function(e) {
    
    cat("Got into error condition!\n")
    return(1)
  },
  warning = function(w) {
    cat("Got into warning condition!\n")
    return(2)
  }
)
#> Got into error condition!

cat("ret =", ret, "\n")
#> ret = 1

Created on 2022-06-15 by the reprex package (v2.0.1)

  • Related