相关疑难解决方法(0)

使用tryCatch跳转到错误时循环的下一个值?

我已经阅读了一些关于tryCatch和cuzzins的其他SO问题,以及文档:

但我还是不明白.

我正在运行一个循环,next如果发生任何一种错误,我想跳过:

for (i in 1:39487) {

  # EXCEPTION HANDLING
  this.could.go.wrong <- tryCatch(
                           attemptsomething(),
                           error=function(e) next
                         )
  so.could.this <- tryCatch(
                     doesthisfail(),
                     error=function(e) next
                   )

  catch.all.errors <- function() { this.could.go.wrong; so.could.this; }
  catch.all.errors;


  #REAL WORK
  useful(i); fun(i); good(i);

  }  #end for
Run Code Online (Sandbox Code Playgroud)

(顺便说一句,没有next我能找到的文件)

当我跑步时,R鸣喇叭:

Error in value[[3L]](cond) : no loop for break/next, jumping to top level
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么基本点?这tryCatch显然是在for循环中,所以为什么不R知道呢?

error-handling exception-handling r try-catch

57
推荐指数
5
解决办法
8万
查看次数

如何将警告和错误保存为函数的输出?

我正在使用lapply大量项目上的复杂函数,我想保存每个项目的输出(如果有的话)以及生成的任何警告/错误,以便我可以告诉哪个项目产生了哪个警告/错误.

我找到了一种方法来捕捉警告withCallingHandlers(在此描述).但是,我也需要捕获错误.我可以将它包装在一个tryCatch(如下面的代码中),但是有更好的方法吗?

catchToList <- function(expr) {
  val <- NULL
  myWarnings <- NULL
  wHandler <- function(w) {
    myWarnings <<- c(myWarnings, w$message)
    invokeRestart("muffleWarning")
  }
  myError <- NULL
  eHandler <- function(e) {
    myError <<- e$message
    NULL
  }
  val <- tryCatch(withCallingHandlers(expr, warning = wHandler), error = eHandler)
  list(value = val, warnings = myWarnings, error=myError)
} 
Run Code Online (Sandbox Code Playgroud)

此函数的示例输出是:

> catchToList({warning("warning 1");warning("warning 2");1})
$value
[1] 1

$warnings
[1] "warning 1" "warning 2"

$error
NULL

> catchToList({warning("my warning");stop("my error")})
$value …
Run Code Online (Sandbox Code Playgroud)

error-handling r try-catch

39
推荐指数
4
解决办法
2万
查看次数

R Shiny:将警告消息输出到 UI

控制台中会输出警告消息,但是如何让这些警告显示在 UI 中,以便用户无需查看控制台即可看到它们?

r shiny

2
推荐指数
1
解决办法
1807
查看次数

标签 统计

r ×3

error-handling ×2

try-catch ×2

exception-handling ×1

shiny ×1