Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

error handling - tryCatch block in R, returning variable

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...