Reputation: 23550
I have to call a function that throws an error if the arguments didn't satisfy many conditions.
The conditions are so complicated that I cannot try to satisfy them 100% of the time (I would have to re-type all the conditions the function checks internally). Instead, I should just retry calling with different arguments (as many times as necessary to fill my table).
In other languages I can write a catch block around the call.
However, in R tryCatch seems to work differently: you can give code with finally=
, but after executing the finally-code the outer function terminates anyway.
Here is a minimal example:
sometimesError <- function() {
if(runif(1)<0.1) stop("err")
return(1)
}
fct <- function() {
theSum <- 0
while(theSum < 20) {
tryCatch( theSum <- theSum + sometimesError() )
}
return(theSum)
}
fct() # this should always evaluate to 20, never throw error
( I have read "Is there a way to source()
and continue after an error?", and some other posts but I dont think they apply here. They achieve that the source'd code continues statement-by-statement regardless of error as if it were executing at the top level. I, on the other side, am happy with the called function terminating and it is the caller-code that should continue )
Upvotes: 1
Views: 582
Reputation: 49810
You can pass a function to the error
argument of tryCatch
to specify what should happen when there is an error. In this case, you could just return 0 when there is an error
fct <- function() {
theSum <- 0
while(theSum < 20) {
theSum <- theSum + tryCatch(sometimesError(), error=function(e) 0)
}
return(theSum)
}
As @rawr mentioned in the comments, you could also replace tryCatch
with try
in this case.
fct <- function() {
theSum <- 0
while(theSum < 20) {
try(theSum <- theSum + sometimesError(), silent=TRUE)
}
return(theSum)
}
Upvotes: 1