Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

r - How to retry a statement on error?

How can I simply tell R to retry a statement a few times if it errors? E.g. I was hoping to do something like:

tryCatch(dbGetQuery(...),           # Query database
    error = function(e) {
        if (is.locking.error(e))    # If database is momentarily locked
            retry(times = 3)        # retry dbGetQuery(...) 3 more times
        else {
            # Handle other errors
        }
    }
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I usually put the try block in a loop, and exit the loop when it no longer fails or the maximum number of attempts is reached.

some_function_that_may_fail <- function() {
  if( runif(1) < .5 ) stop()
  return(1)
}

r <- NULL
attempt <- 1
while( is.null(r) && attempt <= 3 ) {
  attempt <- attempt + 1
  try(
    r <- some_function_that_may_fail()
  )
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...