on.exit resides.
on.exit(expression, add = T, frame = sys.parent(), evaluate = F)
expression is omitted, the exit action is canceled
(the last or all actions according to the
add argument).
FALSE, the new expression replaces the old one.
expression.
TRUE, the expression is evaluated immediately in the frame
of the caller of
on.exit. If
FALSE, the expression is
stored unevaluated until being evaluated in
frame just before exiting.
on.exit can be used, for example, to get rid of a
temporary file created by the enclosing function-see the
first example below.
The action will be taken even if an error occurs later in the function.
To use
on.exit solely to trap errors, that is,
not for normal return from the
frame, call
on.exit(expression) initially and then
on.exit()
just prior to returning from the function.
The function
sys.on.exit returns the list of expressions given ot
on.exit
and currently still scheduled to be evaluated.
# Example 1:
# Notice how on.exit is used to remove the temp file
foo <- function(...){
file <- tempfile("foo")
on.exit(unlink(file))
# now work with the temporary file
# knowing that it will be removed when
# the function exits
}
# Example 2:
# Execute the expression only on error conditions
bar <- function(...){
on.exit(cat("An error occurred\\n"))
# do the work
on.exit() # no more errors possible
x # return x as value of function
}