9

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] FALSE

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.

1
  • Note that tryCatch will report only the first error it bumps onto. Commented Mar 7, 2011 at 21:32

3 Answers 3

6

To expand upon mdsumner's point, this is a simple implementation.

sources_correctly <- function(file)
{
  fn <- try(source(file))
  !inherits((fn, "try-error"))
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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)
}

2 Comments

That's what I'm doing, it just seemed clunky. I suppose I was looking for an is.error command.
er, with objects from try that is, not tryCatch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.