Description Usage Arguments Details Value See Also Examples
try
is a wrapper to run an expression that might fail and allow
the user's code to handle error-recovery.
1 |
expr |
an R expression to try. |
silent |
logical: should the report of error messages be suppressed? |
try
evaluates an expression and traps any errors that occur
during the evaluation. If an error occurs then the error
message is printed to the stderr
connection unless
options("show.error.messages")
is false or
the call includes silent = TRUE
. The error message is also
stored in a buffer where it can be retrieved by
geterrmessage
. (This should not be needed as the value returned
in case of an error contains the error message.)
try
is implemented using tryCatch
; for
programming, instead of try(expr, silent = TRUE)
, something like
tryCatch(expr, error = function(e) e)
(or other simple
error handler functions) may be more efficient and flexible.
The value of the expression if expr
is evaluated without error,
but an invisible object of class "try-error"
containing the
error message, and the error condition as the "condition"
attribute, if it fails.
options
for setting error handlers and suppressing the
printing of error messages;
geterrmessage
for retrieving the last error message.
The underlying tryCatch
provides more flexible means of
catching and handling errors.
assertCondition
in package tools is related and
useful for testing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | ## this example will not work correctly in example(try), but
## it does work correctly if pasted in
options(show.error.messages = FALSE)
try(log("a"))
print(.Last.value)
options(show.error.messages = TRUE)
## alternatively,
print(try(log("a"), TRUE))
## run a simulation, keep only the results that worked.
set.seed(123)
x <- stats::rnorm(50)
doit <- function(x)
{
x <- sample(x, replace = TRUE)
if(length(unique(x)) > 30) mean(x)
else stop("too few unique points")
}
## alternative 1
res <- lapply(1:100, function(i) try(doit(x), TRUE))
## alternative 2
## Not run: res <- vector("list", 100)
for(i in 1:100) res[[i]] <- try(doit(x), TRUE)
## End(Not run)
unlist(res[sapply(res, function(x) !inherits(x, "try-error"))])
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.