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, silent = FALSE)

_A_r_g_u_m_e_n_t_s:

    expr: an R expression to try.

  silent: logical: should the report of error messages be suppressed?

_D_e_t_a_i_l_s:

     'try' evaluates an expression and traps any errors that occur
     during the evaluation.  'try' establishes a handler for errors
     that uses the default error handling protocol. It also establishes
     a 'tryRestart' restart that can be used by 'invokeRestart'.

_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 fails. The normal error handling will print
     the same message unless 'options("show.error.messages")' is false
     or the call includes 'silent = TRUE'.

_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. 'tryCatch' provides another means of catching and
     handling errors.

_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)

     ## alternatively,
     print(try(log("a"), 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")
     }
     ## 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"))])

