using try vs TryCatch in R

675 Views Asked by At

My R code is as follows

errors = 0

for(i in c(1:100)){

 tryCatch(expr = {
    API Call
  }, error = {errors=errors+1}, finally = {})

  further code
}

The code is meant to continue execution even if the API call fails and count the number of times error occurred. But I see that if for an iteration there is an error in API call, the code is not executed for further iterations. If I use try(), then I wont be able to count the number of errors.

2

There are 2 best solutions below

7
r2evans On

The error= argument of tryCatch should be a function. If you pre-instantiate errors <- 0 before the for loop, there are a couple of options:

My preferred is to catch and check to see if it inherits "error":

errors <- 0L
for (...) {
  res <- tryCatch({
    ...API call...
  },
    error = function(e) e)
  if (inherits(res, "error")) {
    errors <- errors + 1L
  } else {
    something else here
  }
}

Equivalently with try:

errors <- 0L
for (...) {
  res <- try({
    ...API call...
  }, silent = TRUE)
  if (inherits(res, "try-error")) {
    errors <- errors + 1L
  } else {
    something else here
  }
}

Though the reasons I prefer that may be mostly subjective. Another way would be more internal:

errors <- 0L
for (...) {
  res <- tryCatch({
    ...API call...
  },
    error = function(e) { errors <<- errors + 1L; })
  something else here
}
0
Nir Graham On

# set up scenario
api_call <- function(in_1){
  if(in_1 %in% c(5,7)){
    stop("bad num")
  }
  in_1+.5
}

for(i in 1:10){
  print(api_call(i))
}

# wrap it up
library(purrr)
safe_api_call <- safely(api_call)
for(i in 1:10){
  print(safe_api_call(i)$result)
}

# add counting of errors

error_count <- 0
for(i in 1:10){
  r <- safe_api_call(i)
  print(r$result)
  error_count <- error_count + inherits(r$error,"error")
}
error_count