Search code examples
rrscript

How to ignore/skip exceptions executed in R?


I've tried multiple examples I found on here and elsewhere but it always fails to do what I want.

My R script is simply a configuration validation script, it checks to make sure the user has their environment setup correctly. So I want to try 5 different steps and report on the status of each so that the user can go and fix everything all at once. For example, my first step tests the connection to the database, if that fails I want to print a message and continue on to step 2. But it always halts execution when it errors out and so I only get to the failure and then no more.

I am running the script from command line using RScript.exe on W64. Here's my basic tryCatch, I tried it with the error function and without, it makes no difference, it always breaks on the error.

tryCatch(
    expr = {
       res<- dbGetQuery(con, sql)
       print("SQL query results:")
       print(res)
    }
)

Solution

  • tryCatch catches nothing until you tell it what you want to catch. For instance,

    tryCatch(
        expr = {
           res<- dbGetQuery(con, sql)
           print("SQL query results:")
           print(res)
        },
        error = function(e) NULL
    )
    

    will return NULL when there's an error. Without that line, it is catching nothing.

    Side note: res's existence is not certain. Two scenarios:

    1. res is never defined before now. If there's an error, res will not exist, and any code that follows it will fail with Error: object 'res' not found.

    2. res was defined in a previous code block and is now likely unnecessary. However, if dbGetQuery fails then res will not have been redefined, so it is still present but not related to this query.

    Both situations are problematic. I recommend something like:

    res <- NULL
    res <- tryCatch({
      dbGetQuery(con, sql)
    }, error = function(e) conditionMessage(e))
    if (is.null(res)) {
      print(paste("oops!", res))
    } else {
      print(res)
    }