Domanda

I have a function:

buggy <- function(...) {
    tryCatch({
        itWorked <- FALSE
        stop("I don't like green eggs and ham!")
        itWorked <- TRUE
    }, finally = {
        if ( itWorked )
            return("I do, Sam I am")
        else
            return("I do not like them, Sam I am!")
    })
}

Basically, buggy tries to do some calculations that may or may not succeed (determined by itWorked. The finally clause just makes sure that even if the calculation didn't work, something gets returned (in this case, "I do not like them, Sam I am!").

It works as expected:

> buggy()
Error in tryCatchList(expr, classes, parentenv, handlers) : 
  I don't like green eggs and ham!
[1] "I do not like them, Sam I am!"

Now I want to listen for errors in buggy():

tryCatch( buggy(), 
          error=function(e) message('too bad! there was an error') )

However the error in buggy fails to raise an error in the surrounding tryCatch:

> tryCatch( buggy(), 
+           error=function(e) message('too bad! there was an error') )
[1] "I do not like them, Sam I am!"

I would expect this to say:

'too bad! there was an error'
[1] "I do not like them, Sam I am!"

Can anyone tell me why this does not work? Do I somehow need to 'raise' errors from within buggy?

È stato utile?

Soluzione

The outer tryCatch() doesn't give you the message stored in its error argument for exactly the same reason that the following call does not:

tryCatch("I do not like them, Sam I am!",
    error=function(e) message('too bad! there was an error') )
# [1] "I do not like them, Sam I am!"

The message in the error argument two lines up would only be invoked if buggy() returned an error. But instead (thanks to the work of the tryCatch() inside of it), buggy() just returns a character vector, and tryCatch() has nothing to 'catch':

value <- buggy()
value
# [1] "I do not like them, Sam I am!"

# And, to belabor the point:
identical(buggy(), "I do not like them, Sam I am!")  
# [1] TRUE
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top