Handling Errors in R Programming

Error Handling is a process in which we deal with unwanted or anomalous errors which may cause abnormal termination of the program during it’s execution. In R Programming, there are basically two ways in which we can implement an error handling mechanism. Either we can directly call the functions like stop() or warning(), or we can use the error options such as “warn” or “warning.expression”. The basic functions that one can use for error handling in the code :

  • stop(…) : It halts the evaluation of the current statement and generates a message argument. The control is returned to the top-level.
  • waiting(…) : It’s evaluation depends on the value of the error option warn. If the value of warn is negative then it is ignored. In case the value is 0 (zero) they are stored and printed only after the top-level function completes its execution. If the value is 1 (one) then it is printed as soon as it has been encountered while if the value is 2 (two) then immediately the generated warning is converted into an error.
  • tryCatch(…) : It helps to evaluate the code and assign the exceptions.

Condition Handling in R

Generally, if we encounter any unexpected errors while executing a program we need an efficient and interactive way to debug the error and know what went wrong. However, some errors are expected but sometimes the models fail to fit and throw an error. 

There are basically three methods to handle such conditions and error in R :

  • try() : it helps us to continue with the execution of the program even when an error occurs.
  • tryCatch() : it helps to handle the conditions and control what happens based on the conditions.
  • withCallingHandlers() : it is an alternative to tryCatch() that takes care of the local handlers.

try-catch-finally in R

Unlike other programming languages such as Java, C++ and so on, the try-catch-finally statements is used as a function in R. The main two conditions to be handled in tryCatch() are “errors” and “warnings”.

Syntax:



check = tryCatch({
    expression
}, warning = function(w){
    code that handles the warnings
}, error = function(e){
    code that handles the errors
}, finally = function(f){
    clean-up code
})

Example: 

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program illustrating error handling
# Division by 0 error
# Getting an argument
arg <- commandArgs(trailingOnly=TRUE)
a <- arg[1]
  
# Defining a division function and checking for errors
div <- function(no, a) 
{
    if (a == 'warning'
    {
        val <- 'It is a warning'
        warning("warning message")
    
    else if (a == 'error')
    {
        val <- 'It is an error'
        stop("error!!")
    
    else
    {
        val <- no/as.numeric(a)
    }
    return (val)
}
  
# Evaluation of tryCatch
check <- tryCatch({
  
b <- 12
e <- div(b, a)
  
},
warning = function(war)
{
    print(paste("MY WARNING: ", war))
},
error = function(err)
{
    print(paste("MY ERROR: ", err))
}, 
finally = function(f)
{
    print(paste("e: ", e))
}) 
# End of tryCatch
  
print(paste("Result: ", check))

chevron_right


Input : Example.Rscript 0.1
Output : Result: It is an error

Input : Example.Rscript 2
Output : Result: 6

withCallingHandlers() in R

In R, withCallingHandlers() is a variant of tryCatch(). The only difference is tryCatch() deals with exiting handlers while withCallingHandlers() deals with local handlers. 

Let us understand the difference with an example.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to differentiate between 
# tryCatch() and withCallingHandlers()
  
A <- function() cat("Hello \n")
  
# tryCatch()
tryCatch(message = message_handler, 
{
    message("Hey")
}) # this will print only Hello
  
# withCallingHandlers()
withCallingHandlers(message = message_handler,
{
    message("Hi")
}) # this will print Helllo as well as Hi

chevron_right


Output: Hello
Hello
Hi



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.