Skip to content
Prev 253149 / 398500 Next

tryCatch - Continuing for/next loop after error

The stuff about the error handle requiring an argument and
not being able to call next() from outside of a loop is true,
but you do not need to do the assignment inside the main expression
of tryCatch().  I find it clearer if you do the assignment outside
of tryCatch() so the main expression can return one thing and the
error handler can return something else.  You can use this in an
*apply() function or a for loop, while the assignment-in-tryCatch()
won't work in a *apply() call.  E.g., suppose we have a function
that only works on positive odd integers:
  o <- function (x) {
      stopifnot(x%%2 == 1, x>0)
      (x - 1)/2
  }
Then you can use tryCatch to flag the bad inputs with a code
that tells you about the bad input:
  > sapply(1:5, function(i)tryCatch(o(i), error=function(e)-1000-i))
  [1]     0 -1002     1 -1004     2
or with a for loop where you don't have to prefill the output
vector with any particular values:
  > value <- numeric(5)
  > for(i in 1:5) value[i] <- tryCatch(o(i), error=function(e)-1000-i)
  > value
  [1]     0 -1002     1 -1004     2

To do that with with an assignment in the main expression of tryCatch
would require something like
  > value <- -1000 -(1:5)
  > for(i in 1:5) tryCatch(value[i] <- o(i), error=function(e)NULL)
  > value
  [1]     0 -1002     1 -1004     2
which seems to me uglier and harder to follow since value's entries
are filled in different parts of the code.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com