Exit Expression For a Function

DESCRIPTION:

Evaluates an expression upon exiting the function in which on.exit resides.

USAGE:

on.exit(expression, add = T, frame = sys.parent(), evaluate = F) 

OPTIONAL ARGUMENTS:

expression
S-PLUS expression.

If expression is omitted, the exit action is canceled (the last or all actions according to the add argument).
add
logical flag: if an expression is supplied, and an exit expression already exists for this frame, should the new expression be added to the current one? If FALSE, the new expression replaces the old one.
frame
an integer or expression that evaluates to an integer giving the frame in which to evaluate the expression.
evaluate
logical flag: if 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.

DETAILS:

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.

SEE ALSO:

, , for , for .

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 
}