1

I use tryCatch to handle warnings and errors in order to write a log file and secure my code. It write the log correctly with cat when tryCatch returns a success or an error but my problem is the loop execution is stopped when a warning is encountered.

Whitout the tryCatch the loop is not interrupted by warning() so it is not clear for me what's happening here because warning should not beaks loop.

Breaking loop when "warnings()" appear in R

Loop not interrupted :

>list <- c(1:10)
    for(i in list){
      warning(i)}

Warning: 1
Warning: 2
Warning: 3
Warning: 4
Warning: 5
Warning: 6
Warning: 7
Warning: 8
Warning: 9
Warning: 10
> 

Loop interrupted :

>tryCatch(
  {
    list <- c(1:10)
    for(i in list){
      warning(i)
    }
  },
  error=function(cond) {
    message("ERROR: ", cond)
  },
  warning=function(cond) {
    message("WARNING: ", cond)
  } 
)

WARNING: simpleWarning in doTryCatch(return(expr), name, parentenv, handler): 1
> 

Thank you,

Community
  • 1
  • 1
Florent
  • 1,791
  • 22
  • 40
  • what was the original warning message ? – joel.wilson Nov 10 '16 at 11:03
  • It's `There is a warning downloading the symbols list, here's the original warning: missing values removed from data` – Florent Nov 10 '16 at 11:06
  • could you run in debug mode and examine on which case is a warning created? Is it that if a warning occurs, You are still assigning it to "download" and later when you use "download" it errors out! We will need more details on what/when an warning occurs and at that situation what gets assigned to "download" – joel.wilson Nov 10 '16 at 11:28
  • Hi Joel, the warning is created when `to.weekly` is called because there are `NA` in the xts. But this is not a problem when `tryCatch` doesn't handle errors and warnings (i.e. the loop continues without being interrupted). I could prevent this warning by applying `na.omit()` to the `ticker` object but this is not a solution to me because I want to log further & unexpected warnings and errors. – Florent Nov 10 '16 at 11:42
  • I changed the code above with a reproductible example. Hope it's help. – Florent Nov 10 '16 at 14:39

0 Answers0