R 中的 tryCatch 在出错时执行

问题描述 投票:0回答:1

在 R 中使用 tryCatch 时是否可以执行某些命令以防出错?我正在使用下面的代码,但它不执行 X = alternative_value

tryCatch(
{
  X = certain_function_that_sometimes_returns_error      
},
error=function(e) {
  X = alternative_value
})
r error-handling try-catch
1个回答
26
投票

将您的

tryCatch
直接分配给
x

foo <- function() stop("hello")
bar <- function() 'world'
    
x <- tryCatch( 
  {
    foo()
  },
  error = function(e) {
    bar()
  }
)
    
x
# [1] "world"
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.