Error in tryCatch doesn't work

Hey guys,

I want to get data by using my GetRemoteData-Function. Sometimes data isn't available, an Error occurs and R stops running my code. In that case I want to use a tryCatch to go on. My code lookes like this:

  tryCatch({
        
        data <- GetRemoteData(source = "Montel", requestType = "trade", fromDate = today, toDate = "",v.ids = c("EEX DEB WKND0"), nRetry = 0)
        
      }, 
      
      error = function(data) {
        
        matrix <- matrix(1:9, nrow = 3, ncol = 3)
       

      })

It works fine when the data is available. But when it's not, no matrix was created or rather the matrix doesn't exist outside the tryCatch. Why?

Greets Christina

tell the error function what to return :

tryCatch({
  
  data <- GetRemoteData(source = "Montel", 
                        requestType = "trade", 
                        fromDate = today, 
                        toDate = "",
                        v.ids = c("EEX DEB WKND0"), 
                        nRetry = 0)
}, 
error = function(data) {
  matrix <- matrix(1:9, nrow = 3, ncol = 3)
  matrix 
})

If a function is to return a value, that value should be the last thing before exiting the function, your error function assigned a matrix to a variable 'matrix' but then didnt return it. Naming it, doesnt seem worthwhile so better code might be

tryCatch({
  
  data <- GetRemoteData(source = "Montel",
                        requestType = "trade", 
                        fromDate = today,
                        toDate = "",
                        v.ids = c("EEX DEB WKND0"), 
                        nRetry = 0)
}, 
error = function(data) {
  matrix(1:9, nrow = 3, ncol = 3)
})
1 Like

Oh, thank you! Now it works!!!! :slight_smile: :slight_smile:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.