try(expr, silent = FALSE, outFile = getOption("try.outFile", default = stderr()))
| 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. |
# 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)