0

want to understand how to use tryCatch in R.

1. tryCatch(stop("!"), error = function(e) "An error")

[1] "An error"

Question: how does the function run? stop generates the error, but what's the use of following function 'error'? what is the meaning of argument 'e'?

2. show_condition <- function(code) { tryCatch(code, error = function(c) "error", warning = function(c) "warning", message = function(c) "message" ) }

show_condition(stop("!"))

[1] "error"

show_condition(warning("?!"))

[1] "warning"

show_condition(message("?"))

[1] "message"

Question: what's the meaning of 'c'? where is 'c' from? why the different return depends on the code?

Gamp
  • 309
  • 1
  • 5
  • 15
  • Did you at least read the `?tryCatch` help page? Are you completely new to R? – MrFlick Jul 19 '17 at 17:25
  • The function is just an anonymous function. It *must* take an argument, because `tryCatch` will pass in the error as the argument, but you can call the argument whatever you want: `function(a)`, `function(e)`, `function(the_error_i_got)`, doesn't matter. These simple examples don't *do anything* with the error, they just return a string, but you could use a more complex function that does different things depending what the error is. – Gregor Thomas Jul 19 '17 at 17:26
  • For question 2 - this is demonstrating that `tryCatch` can have different behavior for warnings, errors, and messages. I'm confused by your question: *"why the different return depends on the code?"* Different inputs lead to different outputs. This should not be a surprise. – Gregor Thomas Jul 19 '17 at 17:31

0 Answers0