\HeaderA{on.exit}{Function Exit Code}{on.exit}
\keyword{programming}{on.exit}
\begin{Description}\relax
\code{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 \code{on.exit()}, then
the current \code{on.exit} code is removed.

\code{on.exit} is a primitive function so positional matching is
used and names of supplied arguments are ignored.
\end{Description}
\begin{Usage}
\begin{verbatim}
on.exit(expr, add = FALSE)
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{expr}] an expression to be executed.
\item[\code{add}] if TRUE, add \code{expr} to be executed after any previously
set expressions; otherwise (the default) \code{expr} will overwrite
any previously set expressions.
\end{ldescription}
\end{Arguments}
\begin{Details}\relax
Where \code{expr} was evaluated changed in \R{} 2.8.0, and the following
applies only to that and later versions.

The \code{expr} argument passed to \code{on.exit} is recorded without
evaluation.  If it is not subsequently removed/replaced by another
\code{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 \code{expr} use
\code{\LinkA{substitute}{substitute}} or similar.
\end{Details}
\begin{Value}
Invisible \code{NULL}.
\end{Value}
\begin{References}\relax
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)
\emph{The New S Language}.
Wadsworth \& Brooks/Cole.
\end{References}
\begin{SeeAlso}\relax
\code{\LinkA{sys.on.exit}{sys.on.exit}} which returns the expression stored for use
by \code{on.exit()} in the function in which \code{sys.on.exit()} is
evaluated.
\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
require(graphics)

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

\end{ExampleCode}
\end{Examples}

