R中的tryCatch块,返回变量

时间:2018-01-22 22:28:18

标签: r error-handling try-catch

所以,我试图了解R.中的tryCatch的范围和功能。

以下一行:

arima(rep(1,3), order = c(1,0,0))

生成警告和错误,但是在tryCatch块中,只有警告函数返回值。如何获取警告和错误的返回值?

tryTest = tryCatch(
  {
    arima(rep(1,3), order = c(1,0,0))
  }, 
  warning = function(w) {

    print('this is warning')
    print(w)
    return('return string from warning')
  },
  error = function(e) {
    print('this is error')
    print(e)
    return('return string from error')
  },
  finally = {}
)

print(tryTest)

仅生成:

 "return string from warning"

1 个答案:

答案 0 :(得分:1)

R中的

tryCatch允许您在出错时为变量赋值。以下是两个最小的例子:

my_logo <- tryCatch(
{
  my_logo <- RCurl::getURLContent("https://invalid.website")
},
error = function(cond){
  my_logo <- "there is no image"
},
finally = {
  #pass
})

> my_logo
[1] "there is no image"

my_var <- tryCatch(
{
  my_var <- "a"/1
},
error = function(cond){
  my_var <- "foo"
},
finally = {
  #pass
})

> my_var
[1] "foo"

同样,您可以按照已知的方式返回警告值。您不应该编写tryCatch语句,以便它可以同时遇到错误和警告。我甚至不确定这是否可行。

编辑:为了完整起见,我要添加一个警告示例:

my_var <- tryCatch(
{
  warning()
  my_var <- "a"/1
},
warning = function(cond){
  print("There was a warning")
  return("bar")
},
error = function(cond){
  my_var <- "foo"
  print("This message will not be printed.")
},
finally = {
  #pass
})
[1] "There was a warning"
> my_var
[1] "bar"