[Rd] tryCatch in on.exit()

William Dunlap wdunlap at tibco.com
Fri Dec 1 23:16:01 CET 2017


Things work as I would expect if you give stop() a condition object instead
of a string:

makeError <- function(message, class = "simpleError", call = sys.call(-2)) {
    structure(list(message=message, call=call), class=c(class, "error",
"condition"))
}
f0 <- function() {
    on.exit(tryCatch(expr = stop("pb. in f0's on.exit"),
                     error = function(e)cat("[error] caught",
paste(collapse="/", class(e)), ":", conditionMessage(e), "\n")))
    stop("pb. in f0")
}
f1 <- function() {
    on.exit(tryCatch(expr = stop(makeError("pb. in f1's on.exit",
class="simpleError")),
                     error = function(e)cat("[error] caught",
paste(collapse="/", class(e)), ":", conditionMessage(e), "\n")))
    stop(makeError("pb. in f1", class="simpleError"))
}
catch <- function(FUN) {
    tryCatch(
        expr = FUN(),
        error = function(e)paste("[error] caught", paste(collapse="/",
class(e)), ":", conditionMessage(e)))
}
catch(f0) # calls stop("string")
#[error] caught simpleError/error/condition : pb. in f0's on.exit
#[1] "[error] caught simpleError/error/condition : pb. in f0's on.exit"
catch(f1) # calls stop(conditionObject)
#[error] caught simpleError/error/condition : pb. in f1's on.exit
#[1] "[error] caught simpleError/error/condition : pb. in f1"


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Fri, Dec 1, 2017 at 12:58 PM, William Dunlap <wdunlap at tibco.com> wrote:

> The following example involves a function whose on.exit()
> expression both generates an error and catches the error.
> The body of the function also generates an error.
>
> When calling the function wrapped in a tryCatch, should
> that tryCatch's error function be given the error from the
> body of the function, since the one from the on.exit has
> already been dealt with?  Currently the outer tryCatch gets
> the error from the on.exit expression.
>
> xx <- function() {
>   on.exit(tryCatch(
>     expr = stop("error in xx's on.exit"),
>     error=function(e) {
>       cat("xx's on.exit caught error: <<", conditionMessage(e), ">>\n",
> sep="")
>     }))
>   stop("error in body of xx")
> }
> zz <- tryCatch(xx(), error=function(e)paste("outer tryCatch caught error
> <<", conditionMessage(e), ">>", sep=""))
> #xx's on.exit caught error: <<error in xx's on.exit>>
> zz
> #[1] "outer tryCatch caught error <<error in xx's on.exit>>"
>
>
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
>

	[[alternative HTML version deleted]]



More information about the R-devel mailing list