Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用tryCatch和source_R_Error Handling_Try Catch - Fatal编程技术网

使用tryCatch和source

使用tryCatch和source,r,error-handling,try-catch,R,Error Handling,Try Catch,假设我有两个R文件:correct.R和break.R。使用tryCatch检查错误的最佳方法是什么 目前,我有 > x = tryCatch(source("broken.R"), error=function(e) e) > x <simpleError in source("broken.R"): test.R:2:0: unexpected end of input 1: x = { ^> > y = tryCatch(source("cor

假设我有两个R文件:
correct.R
break.R
。使用
tryCatch
检查错误的最佳方法是什么

目前,我有

> x = tryCatch(source("broken.R"), error=function(e) e)
> x
 <simpleError in source("broken.R"): test.R:2:0: unexpected end of input
  1: x = {
     ^>
> y = tryCatch(source("correct.R"), error=function(e) e)
> y
 $value
 [1] 5

 $visible
 [1] FALSE
>x=tryCatch(源(“断开的.R”),错误=function(e)e)
>x
>y=tryCatch(源(“correct.R”),error=function(e)e)
>y
美元价值
[1] 5
$visible
[1] 假的
但是,我构造
tryCatch
的方式意味着我必须询问
x
y
对象,以确定是否存在错误

有更好的方法吗



这个问题来自教学。100名学生上传他们的R脚本,我运行脚本。说句好话,我计划创建一个简单的函数来确定它们的函数源是否正确。它只需要返回TRUE或FALSE。

也许我没有考虑到这一点,但由于您只是在寻找布尔值,您可以测试
$visible
是否存在:

y <- tryCatch(source("broken.R"), error=function(e) e)
works <- !is.null(y$visible) #y$visible would be null if there were an error
试试这个:

> tryCatch(stop("foo"), error = function(e) {
+ cat(e$message, "\n")
+ FALSE
+ })
foo 
[1] FALSE

可选的,你应该考虑哈德利的>测试:包:

> expect_that(stop("foo"), is_a("numeric"))
Error in is.vector(X) : foo

为了扩展mdsumner的观点,这是一个简单的实现

sources_correctly <- function(file)
{
  fn <- try(source(file))
  !inherits((fn, "try-error"))
}

sources\u正确地说,这就是我正在做的,它看起来很笨重。我想我在寻找一个
is.error
command.er,对象来自try-that,而不是tryCatch请注意
tryCatch
将只报告它遇到的第一个错误。
sources_correctly <- function(file)
{
  fn <- try(source(file))
  !inherits((fn, "try-error"))
}