try                   package:base                   R Documentation

_T_r_y _a_n _E_x_p_r_e_s_s_i_o_n _A_l_l_o_w_i_n_g _E_r_r_o_r _R_e_c_o_v_e_r_y.

_D_e_s_c_r_i_p_t_i_o_n:

     `try' is a wrapper to run an expression that might fail and allow
     the user's code to handle error-recovery.

_U_s_a_g_e:

     try(expr, first = TRUE)

_A_r_g_u_m_e_n_t_s:

    expr: an R expression to try

   first: not for user use!

_D_e_t_a_i_l_s:

     `try' is a user-friendly wrapper to `restart'. The argument
     `first' is used to record if `restart' has already been used, and
     so ensure that `restart' is called only once.

_V_a_l_u_e:

     The value of the expression if `expr' is evaluated without error,
     but an invisible object of class `"try-error"' containing the
     error message if it if fails. The normal error handling will print
     the same message unless `options("show.error.messages")' is false.

_S_e_e _A_l_s_o:

     `options' for setting error handlers and suppressing the printing
     of error messages; `geterrmessage' for retrieving the last error
     message.

_E_x_a_m_p_l_e_s:

     ## 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)

     ## run a simulation, keep only the results that worked.
     set.seed(123)
     x <- rnorm(50)
     doit <- function(x)
     {
         x <- sample(x, replace=TRUE)
         if(length(unique(x)) > 30) mean(x)
         else stop("too few unique points")
     }
     options(show.error.messages = FALSE)
     ## alternative 1
     res <- lapply(1:100, function(i) try(doit(x)))
     ## alternative 2
     res <- vector("list", 100)
     for(i in 1:100) res[[i]] <- try(doit(x))
     options(show.error.messages = TRUE)
     unlist(res[sapply(res, function(x) !inherits(x, "try-error"))])

