Using tryCatch and source
Suppose I have two R files: correct.R
and broken.R
. What would be the best way of using tryCatch
to check for errors?
Currently, I have
> 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] FA开发者_StackOverflowLSE
However, the way I've constructed the tryCatch
means that I have to interrogate the x
and y
objects to determine if there has been an error.
Is there a better way of doing this?
The question comes from teaching. 100 students upload their R scripts and I run the scripts. To be nice, I'm planning on creating a simple function that determines if their function sources correctly. It only needs to return TRUE or FALSE.
Try this:
> tryCatch(stop("foo"), error = function(e) {
+ cat(e$message, "\n")
+ FALSE
+ })
foo
[1] FALSE
Alternatively, you should consider Hadley's testthat
package:
> expect_that(stop("foo"), is_a("numeric"))
Error in is.vector(X) : foo
To expand upon mdsumner's point, this is a simple implementation.
sources_correctly <- function(file)
{
fn <- try(source(file))
!inherits((fn, "try-error"))
}
Maybe I'm underthinking this, but since you're just looking for the boolean, you can just test for the existence of the $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
Does that solve what you're looking for? You could wrap it in a loop (or use lapply
) like:
for(i in 1:length(students)) {
works[i] <- !is.null(tryCatch(source(student_submissions[i]), error=function(e) e)$visible)
}
精彩评论