Error handling with tryCatch in R

   Errors can be handled with tryCatch() function in R. Usually the process will be stopped if an error happens during the execution. However, a better script should correctly handle the potential errors and do error case actions without terminating the process. 
   Here, we will see a basic error handling method with tryCatch() function in R
Let's see an example. Below code converts a value into R date-time format. The value can be either time or NA value.

1 target_time=Sys.time()     # default value
2 value="2017/11.22 10:10"   # wrong value
3 if(!is.na(value))
4   target_time<- as.POSIXct(value)
5
6 print(
target_time)


After running the script, the error message will be thrown and a process will be stopped in line 4.

Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format


We'll implement a try-catch method to handle this error and move to the next command without termination. Below is a general try-catch implementation method in R.

tryCatch(
  {
    # expressions
    # potential errors might happen here.

  },
  error=function(e)
  {
    # error handling
  },
  finally=
  {
    # expression before  exit
  }
)


We'll add our time conversion process in the brackets of the tryCatch() function.

target_time=Sys.time()    
tryCatch(
  {
    value="2017/11.22 10:10"       # wrong value
    if(!is.na(value))
      target_time <- as.POSIXct(value)
  },
  error=function(e)
  {
    print(paste("Error! Invalid value:",value))
  },
  finally=
  {
    print(paste("Default time is used:",target_time))
  }
)
print(paste("target_time:",
target_time))


We'll run the script and check the result.

[1] "Error! Invalid value: 2017/11.22 10:10"
[1] "Default time is used: 2017-11-24 14:38:31"
[1] "target_time: 2017-11-24 14:38:31"

   The output shows that we could easily handle the error and escaped from the unnecessary termination of the script with the help of tryCatch() function. You may find more options and usage patterns of this function by checking the help page of the function, help(tryCatch).

   In this tutorial, we've learned how to use try-catch function in R. Thank you for reading!

No comments:

Post a Comment