tryCatch in r

Published by onesixx on

http://mazamascience.com/WorkingWithData/?p=912
result = tryCatch({
    #expr
  }, warning=function(w){
    print("warning-handler-code")
    #warning-handler-code
  }, error=function(e){
    print("error-handler-code")
    #error-handler-code
  }, finally={
    print("cleanup-code")
    #cleanup-code
  }
)

example

tryCatch({
    data.oac.null <- rbind(data.oac.null, data.oac[[j]][[m-i]])
    cat("sheet",m-i, "")
  }, error=function(e){
    cat("ERROR :",conditionMessage(e), "\
")
  }
)
tryCatch({
    data.oac.null <- rbind(data.oac.null, data.oac[[j]][[m-i]])
    cat("sheet",m-i, "")
  }, error=function(e){
    cat("ERROR :",conditionMessage(e), "\
")
  }
)
lapply(1:10, function(i) {
\ttryCatch({
  \tif(i %% 2) {
\t  kkk 
  \t} else {
  \t  cat( glue("good,{i}"), "\
")
  \t} 
\t}, warning = function(e) {
    warning(glue("warning in Ticker:{i}"))
  }, error = function(e){
  \twarning(glue("Error in Ticker:{i}"))
  })
}) %>% invisible()



# good,2 
# good,4 
# good,6 
# good,8 
# good,10 
# Warning messages:
# 1: In value[[3L]](cond) : Error in Ticker:1
# 2: In value[[3L]](cond) : Error in Ticker:3
# 3: In value[[3L]](cond) : Error in Ticker:5
# 4: In value[[3L]](cond) : Error in Ticker:7
# 5: In value[[3L]](cond) : Error in Ticker:9
Categories: R Programming

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x