Nested tryCatch is not a bug trap?

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

In principle, it buggytries to perform some calculations, which may or may not be successful (determined itWorked. The sentence finallysimply ensures that even if the calculation does not work, something is 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, an error in buggycannot cause an error in the environment 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 someone tell me why this is not working? Do I somehow need to "raise" errors from buggy?

+3
source share
1 answer

tryCatch() , error, , :

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!"

error , buggy() . ( tryCatch() ), buggy() , tryCatch() , "":

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
+2

All Articles