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)

Arguments

expr an expression. If expr is omitted, the exit action is cancelled (the last or all actions, according to the add argument).
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.

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
stop, return, .First for .Last, sys.call for sys.on.exit.
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
}
# 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
}
Package base version 4.0.0-28
Package Index