R: Function Exit Code

on.exit {base} | R Documentation

## Function Exit Code

### Description

`on.exit` records the expression given as its argument as needing to be executed when the current function exits (either naturally or as the result of an error). This is useful for resetting graphical parameters or performing other cleanup actions.

If no expression is provided, i.e., the call is `on.exit()`, then the current `on.exit` code is removed.

### Usage

    on.exit(expr = NULL, add = FALSE, after = TRUE)

### Arguments

`expr` | an expression to be executed.
`add` | if TRUE, add `expr` to be executed after any previously set expressions (or before if `after` is FALSE); otherwise (the default) `expr` will overwrite any previously set expressions.
`after` | if `add` is TRUE and `after` is FALSE, then `expr` will be added on top of the expressions that were already registered. The resulting last in first out order is useful for freeing or closing resources in reverse order.

### Details

The `expr` argument passed to `on.exit` is recorded without evaluation. If it is not subsequently removed/replaced by another `on.exit` call in the same function, it is evaluated in the evaluation frame of the function when it exits (including during standard error handling). Thus any functions or variables in the expression will be looked for in the function and its environment at the time of exit: to capture the current value in `expr` use `substitute` or similar.

If multiple `on.exit` expressions are set using `add = TRUE` then all expressions will be run even if one signals an error.

This is a ‘special’ primitive function: it only evaluates the arguments `add` and `after`.

### Value

Invisible `NULL`.

### References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

### See Also

`sys.on.exit` which returns the expression stored for use by `on.exit()` in the function in which `sys.on.exit()` is evaluated.

### Examples

    require(graphics)

    opar <- par(mai = c(1,1,1,1))
    on.exit(par(opar))

[Package base version 4.0.5 Index]