Assigning a value in exception handling in R

て烟熏妆下的殇ゞ 提交于 2019-12-10 15:48:56

问题


 while(bo!=10){
  x = tryCatch(getURLContent(Site, verbose = F, curl = handle),
            error = function(e) {
               cat("ERROR1: ", e$message, "\n")
               Sys.sleep(1)
               print("reconntecting...")
               bo <- bo+1
               print(bo)
               })
  print(bo)
  if(bo==0) bo=10 
}

I wanted to try reconnecting each second after the connection failed. But the new assignment of the bo value is not effective. How can i do that? Or if you know how to reconnect using RCurl options (I really didn't find a thing) it would be amazing.

Every help is appreciated


回答1:


The problem is the b0 scope of the assignment. However, I find try a little more friendly than tryCatch. This should work:

while(bo!=10){
    x = try(getURLContent(Site, verbose = F, curl = handle),silent=TRUE)
    if (class(x)=="try-error") {
           cat("ERROR1: ", x, "\n")
           Sys.sleep(1)
           print("reconnecting...")
           bo <- bo+1
           print(bo)
     } else {
           break
     } 
}

The above attempts 10 times to connect to the site. If any of this time succeeds, it exits.




回答2:


Create a variable outside the scope of tryCatch(), and update using <<-

bo <- 0
while(bo!=10){
    x = tryCatch(stop("failed"),
      error = function(e) {
          bo <<- bo + 1L
          message("bo: ", bo, " " conditionMessage(e))
    })
}

Or use the return value as a sentinel for success

x <- 1
while (is.numeric(x)) {
    x = tryCatch({
        stop("failed")
    }, error = function(e) {
        message("attempt: ", x, " ", conditionMessage(e))
        if (x > 10) stop("too many failures", call.=FALSE)
        x + 1
    })
}


来源:https://stackoverflow.com/questions/28969070/assigning-a-value-in-exception-handling-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!