如何重试错误语句? [英] How to retry a statement on error?

查看:138
本文介绍了如何重试错误语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果错误,我怎么能简单地告诉R重试一次语句?例如。我希望做一些像:

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
        }
    }
)


推荐答案

我通常将 try block放在一个循环中,
,当它不再失败或达到最大尝试次数。

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()
  )
} 

这篇关于如何重试错误语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆