Rev 79594 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
% File src/library/base/man/conditions.Rd% Part of the R package, https://www.R-project.org% Copyright 1995-2020 R Core Team% Distributed under GPL 2 or later\name{conditions}\alias{conditions}\alias{condition}\alias{computeRestarts}\alias{conditionCall}\alias{conditionMessage}\alias{findRestart}\alias{invokeRestart}\alias{tryInvokeRestart}\alias{invokeRestartInteractively}\alias{isRestart}\alias{restartDescription}\alias{restartFormals}\alias{signalCondition}\alias{simpleCondition}\alias{simpleError}\alias{simpleWarning}\alias{simpleMessage}\alias{errorCondition}\alias{warningCondition}\alias{tryCatch}\alias{withCallingHandlers}\alias{withRestarts}\alias{suspendInterrupts}\alias{allowInterrupts}\alias{globalCallingHandlers}\alias{.signalSimpleWarning}\alias{.handleSimpleError}\alias{.tryResumeInterrupt}\alias{as.character.condition}\alias{as.character.error}\alias{conditionCall.condition}\alias{conditionMessage.condition}\alias{print.condition}\alias{print.restart}\title{Condition Handling and Recovery}\description{These functions provide a mechanism for handling unusual conditions,including errors and warnings.}\usage{tryCatch(expr, \dots, finally)withCallingHandlers(expr, \dots)globalCallingHandlers(\dots)signalCondition(cond)simpleCondition(message, call = NULL)simpleError (message, call = NULL)simpleWarning (message, call = NULL)simpleMessage (message, call = NULL)errorCondition(message, ..., class = NULL, call = NULL)warningCondition(message, ..., class = NULL, call = NULL)\method{as.character}{condition}(x, \dots)\method{as.character}{error}(x, \dots)\method{print}{condition}(x, \dots)\method{print}{restart}(x, \dots)conditionCall(c)\method{conditionCall}{condition}(c)conditionMessage(c)\method{conditionMessage}{condition}(c)withRestarts(expr, \dots)computeRestarts(cond = NULL)findRestart(name, cond = NULL)invokeRestart(r, \dots)tryInvokeRestart(r, \dots)invokeRestartInteractively(r)isRestart(x)restartDescription(r)restartFormals(r)suspendInterrupts(expr)allowInterrupts(expr).signalSimpleWarning(msg, call).handleSimpleError(h, msg, call).tryResumeInterrupt()}\arguments{\item{c}{a condition object.}\item{call}{call expression.}\item{cond}{a condition object.}\item{expr}{expression to be evaluated.}\item{finally}{expression to be evaluated before returning or exiting.}\item{h}{function.}\item{message}{character string.}\item{msg}{character string.}\item{name}{character string naming a restart.}\item{r}{restart object.}\item{x}{object.}\item{class}{character string naming a condition class.}\item{\dots}{additional arguments; see details below.}}\details{The condition system provides a mechanism for signaling andhandling unusual conditions, including errors and warnings.Conditions are represented as objects that contain informationabout the condition that occurred, such as a message and the call inwhich the condition occurred. Currently conditions are S3-styleobjects, though this may eventually change.Conditions are objects inheriting from the abstract class\code{condition}. Errors and warnings are objects inheritingfrom the abstract subclasses \code{error} and \code{warning}.The class \code{simpleError} is the class used by \code{stop}and all internal error signals. Similarly, \code{simpleWarning}is used by \code{warning}, and \code{simpleMessage} is used by\code{message}. The constructors by the same names take a stringdescribing the condition as argument and an optional call. Thefunctions \code{conditionMessage} and \code{conditionCall} aregeneric functions that return the message and call of a condition.The function \code{errorCondition} can beused to construct error conditions of a particular class withadditional fields specified as the \code{\dots} argument.\code{warningCondition} is analogous for warnings.Conditions are signaled by \code{signalCondition}. In addition,the \code{stop} and \code{warning} functions have been modified toalso accept condition arguments.The function \code{tryCatch} evaluates its expression argumentin a context where the handlers provided in the \code{\dots}argument are available. The \code{finally} expression is thenevaluated in the context in which \code{tryCatch} was called; thatis, the handlers supplied to the current \code{tryCatch} call arenot active when the \code{finally} expression is evaluated.Handlers provided in the \code{\dots} argument to \code{tryCatch}are established for the duration of the evaluation of \code{expr}.If no condition is signaled when evaluating \code{expr} then\code{tryCatch} returns the value of the expression.If a condition is signaled while evaluating \code{expr} thenestablished handlers are checked, starting with the most recentlyestablished ones, for one matching the class of the condition.When several handlers are supplied in a single \code{tryCatch} thenthe first one is considered more recent than the second. If ahandler is found then control is transferred to the\code{tryCatch} call that established the handler, the handlerfound and all more recent handlers are disestablished, the handleris called with the condition as its argument, and the resultreturned by the handler is returned as the value of the\code{tryCatch} call.Calling handlers are established by \code{withCallingHandlers}. Ifa condition is signaled and the applicable handler is a callinghandler, then the handler is called by \code{signalCondition} inthe context where the condition was signaled but with the availablehandlers restricted to those below the handler called in thehandler stack. If the handler returns, then the next handler istried; once the last handler has been tried, \code{signalCondition}returns \code{NULL}.\code{globalCallingHandlers} establishes calling handlers globally.These handlers are only called as a last resort, after the otherhandlers dynamically registered with \code{withCallingHandlers} havebeen invoked. They are called before the \code{error} global option(which is the legacy interface for global handling of errors).Registering the same handler multiple times moves that handler ontop of the stack, which ensures that it is called first. Globalhandlers are a good place to define a general purpose logger (forinstance saving the last error object in the global workspace) or ageneral recovery strategy (e.g. installing missing packages via the\code{retry_loadNamespace} restart).Like \code{withCallingHandlers} and \code{tryCatch},\code{globalCallingHandlers} takes named handlers. Unlike thesefunctions, it also has an \code{\link{options}}-like interface: youcan establish handlers by passing a single list of named handlers.To unregister all global handlers, supply a single `NULL`. The listof deleted handlers is returned invisibly. Finally, calling\code{globalCallingHandlers} without arguments returns the list ofcurrently established handlers, visibly.User interrupts signal a condition of class \code{interrupt} thatinherits directly from class \code{condition} before executing thedefault interrupt action.Restarts are used for establishing recovery protocols. They can beestablished using \code{withRestarts}. One pre-established restart isan \code{abort} restart that represents a jump to top level.\code{findRestart} and \code{computeRestarts} find the availablerestarts. \code{findRestart} returns the most recently establishedrestart of the specified name. \code{computeRestarts} returns alist of all restarts. Both can be given a condition argument andwill then ignore restarts that do not apply to the condition.\code{invokeRestart} transfers control to the point where thespecified restart was established and calls the restart's handler with thearguments, if any, given as additional arguments to\code{invokeRestart}. The restart argument to \code{invokeRestart}can be a character string, in which case \code{findRestart} is usedto find the restart. If no restart is found, an error is thrown.\code{tryInvokeRestart} is a variant of \code{invokeRestart} thatreturns silently when the restart cannot be found with\code{findRestart}. Because a condition of a given class might besignalled with arbitrary protocols (error, warning, etc), it isrecommended to use this permissive variant whenever you are handlingconditions signalled from a foreign context. For instance, invocationof a \code{"muffleWarning"} restart should be optional because thewarning might have been signalled by the user or from a differentpackage with the \code{stop} or \code{message} protocols. Only use\code{invokeRestart} when you have control of the signalling context,or when it is a logical error if the restart is not available.New restarts for \code{withRestarts} can be specified in several ways.The simplest is in \code{name = function} form where the function isthe handler to call when the restart is invoked. Another simplevariant is as \code{name = string} where the string is stored in the\code{description} field of the restart object returned by\code{findRestart}; in this case the handler ignores its argumentsand returns \code{NULL}. The most flexible form of a restartspecification is as a list that can include several fields, including\code{handler}, \code{description}, and \code{test}. The\code{test} field should contain a function of one argument, acondition, that returns \code{TRUE} if the restart applies to thecondition and \code{FALSE} if it does not; the default functionreturns \code{TRUE} for all conditions.One additional field that can be specified for a restart is\code{interactive}. This should be a function of no arguments thatreturns a list of arguments to pass to the restart handler. The listcould be obtained by interacting with the user if necessary. Thefunction \code{invokeRestartInteractively} calls this function toobtain the arguments to use when invoking the restart. The default\code{interactive} method queries the user for values for theformal arguments of the handler function.Interrupts can be suspended while evaluating an expression using\code{suspendInterrupts}. Subexpression can be evaluated withinterrupts enabled using \code{allowInterrupts}. These functionscan be used to make sure cleanup handlers cannot be interrupted.\code{.signalSimpleWarning}, \code{.handleSimpleError}, and\code{.tryResumeInterrupt} are used internally and should not becalled directly.}\references{The \code{tryCatch} mechanism is similar to Javaerror handling. Calling handlers are based on Common Lisp andDylan. Restarts are based on the Common Lisp restart mechanism.}\seealso{\code{\link{stop}} and \code{\link{warning}} signal conditions,and \code{\link{try}} is essentially a simplified version of\code{tryCatch}.\code{\link{assertCondition}} in package \pkg{tools} \emph{tests}that conditions are signalled and works with several of the abovehandlers.}\examples{tryCatch(1, finally = print("Hello"))e <- simpleError("test error")\dontrun{stop(e)tryCatch(stop(e), finally = print("Hello"))tryCatch(stop("fred"), finally = print("Hello"))}tryCatch(stop(e), error = function(e) e, finally = print("Hello"))tryCatch(stop("fred"), error = function(e) e, finally = print("Hello"))withCallingHandlers({ warning("A"); 1+2 }, warning = function(w) {})\dontrun{{ withRestarts(stop("A"), abort = function() {}); 1 }}withRestarts(invokeRestart("foo", 1, 2), foo = function(x, y) {x + y})##--> More examples are part of##--> demo(error.catching)}\keyword{programming}\keyword{error}