Search code examples
rtry-catch-finally

R tryCatch() - referencing return of expr() in finally?


I am trying to write a function to handle execution of batch jobs, logging errors and stats of the job results.

Is there a way to reference returning value of expr block, from finally block?

my_do <- function(FUN, ...){

  result <- tryCatch({
      FUN(...)
    }, 
    error = function(e) {
      message("error.")
    },
    finaly = {

      # how can I reference the returning value of FUN(...) in finally block?
      # so for example, I can write code like this:

      message(paste("Result dimensions:", dim(expr_result)))
    },
  )

  return(result)
}

Solution

  • If the tryCatch return value is being saved into a variable, such as

    x <- tryCatch({ 1; }, finally = { message("value is ", x); })
    # Error in message("value is ", x) : object 'x' not found
    

    then the answer is no, since the x object does not exist when tryCatch executes finally=.

    However, the code block operates within the parent environment, so you can do this instead:

    tryCatch({ x <- 1; }, finally = { message("value is ", x); })
    # value is 1
    x
    # [1] 1
    

    This relies on the return value being set without error. If there's an error somewhere in the execution, then ... obviously there will be no value to retrieve.