Defensive programming Error Handling in R

“Fail fast!” principles to inform users early with information to debug.

  • Be strict about what you accept. Check the input variable type and use stopifnot() or if and stop()
  • Avoid functions that use non-standard evaluation like subset, transform, and with ?
  • Avoid functions that return different types of output dependent on input

Conditional Error Handling

try() let to continue execution when error occurs

f1 <- function(x) {
    try(log(x))
    10
}

f1("aloha") # will print "aloha" with an error message
try(log(x), silent = TRUE) will not print error message

f1 <- function(x) { try(log(x))}
#class(f1) is either "numeric" or "try-error"

tryCatch() let you specify handler functions to control what happens when a condition is met

read_csv <- function(file, ...) {
  tryCatch(read.csv(file, ...), error = function(c) {
    c$message <- paste0(c$message, "(in ", file, ")")
    stop(c)
   }) 
}
read.csv("bad.csv") 
# error in file(file, "rt"): cannot open the connection

withCallingHandlers() a variant of tryCatch()