tryCatch block in R, returning variable

2019-08-27 23:02发布

So, I am trying to understand scope and functionality of tryCatch in R.

the following line:

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

generates both warning and error, however in tryCatch block only warning function returns value. How can I get access to return value of both warning and error?

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)

produces only:

 "return string from warning"

1条回答
淡お忘
2楼-- · 2019-08-27 23:22

tryCatch in R allows you to assign a value to the variable on error. Here are two minimal examples:

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"

Similarly, you can return a value on warning as you already know. You should not write your tryCatch statement such that it could encounter both error and warning at the same time. I am not even sure if that is possible.


Edit: For completeness, I am adding an example with warning:

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"
查看更多
登录 后发表回答