Search code examples
rerror-handlingtry-catch

tryCatch in R execute in case of error


Is it possible to execute certain commands in case of error when using tryCatch in R ? I am using the code below but it does not execute X = alternative_value

tryCatch(
{
  X = certain_function_that_sometimes_returns_error      
},
error=function(e) {
  X = alternative_value
})

Solution

  • Assign your tryCatch directly to x

    foo <- function() stop("hello")  ## initiate an error using `stop()`
    bar <- function() 'world'
        
    x <- tryCatch( 
      {
        foo()
      },
      error = function(e) {
        bar()
      }
    )
        
    x
    # [1] "world"