try
Continue after errors

Description

Evaluates a possible erroneous expression without exiting to the top-level prompt.

Usage

try(expr, silent = FALSE, outFile = getOption("try.outFile", default = stderr()))

Arguments

expr An expression to evaluate. It is evaluated in the frame of the caller.
silent A logical flag. If TRUE, the error message is not printed. If FALSE (the default), the error message is printed.
outFile The name of a file or a connection object specifying where to print the error message.

Details

try is implemented using the tryCatch function, creating an "error" condition handler to catch any errors.
Value
returns the value of the expression if no error occurred while evaluating the expression. If an error occurred, invisibly returns an object of class "try-error" containing the error message, with an attribute "condition" containing the error condition caught.
See Also
tryCatch.
Examples
# avoid stopping simulation because of bad data points 
set.seed(1) 
inputs <- sapply(1:10, function(i)rpois(1,1)) 
f <- function(x) if(x<1) stop("x<1") else log(x) 
val <- lapply(inputs, function(x)try(f(x))) 
unlist(val[!sapply(val, is, "try-error")]) # extract ones that worked 

rm(x); rm(y) # make sure x, y are not defined. try(x) # Error in tryCatch(expr, error = function(e) invisible(.tryErrorHandle... : # object "x" not found res <- try(x) # Error in tryCatch(expr, error = function(e) invisible(.tryErrorHandle... : # object "x" not found

class(res) # "try-error" res1 <- try(y, silent = TRUE) # no error printout res1 # examine error

x <- runif(20) y <- rnorm(20) res2 <- try(lm(x~y)) res2 # the value of lm(x~y)

Package base version 6.1.1-7
Package Index