tryCatch in R execute in case of error

16,213

Assign your tryCatch directly to x

foo <- function() stop("hello")
bar <- function() 'world'

x <- tryCatch(
    {
        foo()
    },
    error = function(e){
        bar()
    }
)

x
# [1] "world"
Share:
16,213
Kinformationist
Author by

Kinformationist

Updated on June 28, 2022

Comments

  • Kinformationist
    Kinformationist almost 2 years

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