1

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"
user1700890
  • 7,144
  • 18
  • 87
  • 183
  • 2
    Possibly relevant: https://stackoverflow.com/q/34816084/324364 – joran Jan 22 '18 at 22:35
  • 2
    Possibly relevant: https://stackoverflow.com/q/19433848/2563804: As per the answer of @daroczig, `pander::evals("arima(rep(1,3), order = c(1,0,0))")` may do the trick. – hplieninger May 30 '18 at 11:58

1 Answers1

2

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"
Martin
  • 373
  • 4
  • 7