on.exit
Exit Expression For a Function
Description
Evaluates an expression upon exiting the function in which
on.exit resides.
Usage
on.exit(expr = NULL, add = FALSE, after = TRUE)
Arguments
expr |
an expression. If expr is omitted, the exit action
is cancelled (the last or all actions, according to the
add argument).
If used, expr must be the first argument. Arguments are not matched by name.
|
add |
a logical flag.
- If TRUE, if an expression is supplied, and an
exit expression already exists for this frame, the new expression is
added to the current one.
- If FALSE (the default), the new
expression replaces the old one.
If used, add must be the second argument. Arguments are not matched by name.
|
after |
a logical value used when add is TRUE.
- If TRUE, the default, the exit expression is added to the end
of the list of exit expressions.
- If FALSE the exit expression is added to the beginning of the list
of exit expressions.
If used, after must be the third argument. Arguments are not matched by name.
|
Details
For example, you can use on.exit to delete a
temporary file created by the enclosing function (see the
first example below).
The action is 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
call on.exit() just prior to returning from the function.
The function sys.on.exit returns the list of expressions
given to on.exit and still scheduled to be evaluated.
See Also
Examples
# 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
cat(file = file, "Hello, world!\n")
list(file = file, size = file.size(file))
}
(foo_value <- foo())
file.exists(foo_value$file)
# Example 2:
# Execute the expression only on error conditions
bar <- function(x){
on.exit(cat("An error occurred\n"))
stopifnot(x > 0)
on.exit() # no more errors possible
log(x)
}
bar(2)
# Example 3:
# Execute the last exit expression added first
lifo <- function() {
on.exit(cat("A\n"))
on.exit(cat("B\n"), add=TRUE, after=FALSE)
on.exit(cat("C\n"), add=TRUE, after=FALSE)
}
lifo()