0

I am trying to use tryCatch funciton to catch errors and stop runs with personalized and original error messages printed. The expression is to evaluate a+"T", which will surely produce an error. The code will be something like

a <- 1
res <- tryCatch({a+"T"}, 
                 error = function(e) {stop(); print("We get the following errors:"); print(Original_message)})

But this code doesn't work. How can we do all three things together?

1 Answer 1

4

E.g. something like:

a <- 1
res <- tryCatch(
  a+"T", 
  error = function(e) cat("We get the following errors:\n", e$message)
)
We get the following errors:
 non-numeric argument to binary operator

Or perhaps something like:

res <- tryCatch(
  a+"T", 
  error = function(e) stop("We get the following errors:\n", e, call. = FALSE)
)
Error: We get the following errors:
Error in a + "T": non-numeric argument to binary operator

Or

res <- tryCatch(
  a+"T", 
  error = function(e) { cat("We get the following errors:\n"); stop(e) }
)
We get the following errors:
Error in a + "T" : non-numeric argument to binary operator

If you call stop() at the start of your error function, evaluation will stop then and there, and the rest of the function is not run. The error itself (e) contains both the call (e$call) and the error message (e$message). print(e) will show both.

1
  • Fantastic! Thank you so much!
    – Phoebe
    Commented Jul 9 at 1:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.