1

I have been reading through the answers on SO about how to use tryCatch. I really don't understand where the c variable comes from though.

e.g. (via http://adv-r.had.co.nz/Exceptions-Debugging.html#condition-handling)

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"

# If no condition is captured, tryCatch returns the 
# value of the input
show_condition(10)
#> [1] 10

Is c a system variable? Elsewhere others seems to use e in its place?

Community
  • 1
  • 1
drstevok
  • 715
  • 1
  • 6
  • 15

1 Answers1

3

In your code, function(c) "error" is just an anonymous function run by tryCatch in case its code argument raises an error.

An argument of class condition is passed to this anonymous function, and it allows you to get the call that raises the error, and the message generated by R. For example :

R> tryCatch(print(foobar), error=function(c) print(c$message))
[1] "objet 'foobar' introuvable"

As such, c here is just the name you give to the condition passed as an argument, and you can give it any name you want : c, e or even deliciouspizza.

For example :

R> tryCatch(print(foobar), error=function(rcatladies) print(rcatladies$call))
print(foobar)
juba
  • 47,631
  • 14
  • 113
  • 118
  • thanks. So it all depends on the initial function creating (or returning - my terminology is probably wrong) an argument of the appropriate class. If I was using my own function (and hadn't been smart enough to return such an argument), then would the tryCatch method fail? – drstevok Oct 07 '14 at 14:45
  • @drstevok Hmm no, it doesn't depend on your initial function. The anonymous function is called by `tryCatch` in case of error, warning, message, etc. It's `tryCatch` that creates the `condition` argument and passes it to the anonymous function you defined. Not sure I'm really clear here... – juba Oct 07 '14 at 14:49
  • No, that helps ... and I think that is where I was getting confused. I couldn't work out where the `condition` argument was coming from. – drstevok Oct 07 '14 at 15:14