【问题标题】:Use trycatch to run on next loops when detect error检测到错误时使用 trycatch 在下一个循环上运行
【发布时间】:2019-10-19 10:23:09
【问题描述】:

尝试编写一个 trycatch 函数来检测错误。但是循环在检测到错误后不会继续运行。

for(number in 1:10){
    tryCatch({
      user_link = suppressMessages(remoteDriver$findElement(using = 'css selector', x[number]))
    }, error = function(e){ user_link = NA})

    user_link = as.character(user_link$getElementText())

    commentdf1 = data.frame(user_link)
    commentdf = rbind(commentdf,commentdf1)
  }

我希望在循环中运行时有 10 个信息。如果输入user_link = NA是错误的

【问题讨论】:

  • 请发布错误信息。如果user_link 为 NA:as.character(user_link$getElementText()),则后续行将出错。

标签: r


【解决方案1】:

我建议尝试寻找一种替代 tryCatch 的这种用法。它可以使代码更难阅读,使意外错误几乎无法检测到,并且在tryCatch 中使用的任何包更改其代码的情况下,您的代码将停止工作,同时不会产生可区分的错误。

也就是说您的问题不在tryCatch 函数中,而是在user_link$getElementText() 之后的调用中,如果tryCatch 函数导致错误,则会输出不同的错误。

有几种方法可以解决这个问题。最简单的一种是使用next 运算符跳过迭代。在这种情况下,在data.frame 中包含成功的迭代可能是明智的。

for(number in 1:10){
    if(isFALSE(
        tryCatch({
        user_link = suppressMessages(
            remoteDriver$findElement(using = 'css selector', x[number])
        )}, error = function(e) FALSE)
        )
      ) next

    user_link = as.character(user_link$getElementText())

    #Include iteration so we can see which succeeded and which did not.
    commentdf1 = data.frame(user_link, iteration = i)
    commentdf = rbind(commentdf,commentdf1)
  }

除了包含迭代之外,您还可以预先创建整个 data.frame,并使用 commentdf[i, ] <- user_link 估算成功的迭代,这也将加快您的实现速度(如果迭代超过 20 次,则非常明显) .

【讨论】:

  • 感谢您的指导,它现在对我有用。如果检测到错误,我可以检查如何输入“NA”吗?
  • 两种简单的方法是 1) 预先创建 data.frame 并插入行(例如 commentdf <- data.frame(c1 = rep(NA, 10), ....) 之类的东西,使用适当的列和尺寸,然后按照我的答案插入。)或在tryCatch 调用本身的第一部分中包含user_link = as.character(user_link$getElementText())(在您自己的代码中)。您必须确保commentdf1 中的列数始终与commentdf 中的列数匹配。请记住对答案进行投票和/或将答案标记为回答问题,以帮助其他有类似问题的人找到答案。 :-)
  • 或者你可以grep错误信息,捕捉特定错误,让其他意想不到的错误tryCatch(stop('catch this'), error = function(e) if (grepl('catch', e$message)) NA else e)
  • @rawr,这应该不起作用,因为失败的原因应该来自随后对.$getElementText()的调用。手头的问题是@Geo 希望将NA 值放入他的data.frame,这需要在代码本身中进行一些移动。
  • 我指的是这个It can make code much more difficult to read, make unexpected errors almost undetectable and in the case that any package used within tryCatch changes it's code, your code will simply stop working, while yielding no distinguishable error
猜你喜欢
  • 2011-12-26
  • 2013-12-11
  • 2012-04-16
  • 1970-01-01
  • 2017-04-06
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多