Handling Errors in R Programming

28 Dec, 2021
Error Handling is a process in which we deal with unwanted or anomalous errors which may cause abnormal termination of the program during its 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(...): Its evaluation depends on the value of the error option warn. If the value of the warning 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.
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 errors 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.
Unlike other programming languages such as Java, C++, and so on, the try-catch-finally statements are 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: 
R
# R program illustrating error handling# Applying tryCatchtryCatch(                  # Specifying expression  expr = {                         1 + 1    print("Everything was fine.")  },  # Specifying error message  error = function(e){             print("There was an error message.")  },    warning = function(w){          print("There was a warning message.")  },    finally = {                print("finally Executed")  })
Output:
[1] "Everything was fine."
[1] "finally Executed"
In R, withCallingHandlers() is a variant of tryCatch(). The only difference is tryCatch() deals with exiting handlers while withCallingHandlers() deals with local handlers. 
Example:
R
# R program illustrating error handling # Evaluation of tryCatchcheck <- function(expression){ withCallingHandlers(expression,                 warning = function(w){        message("warning:\n", w)        },        error = function(e){        message("error:\n", e)        },        finally = {        message("Completed")        })} check({10/2})check({10/0})check({10/'noe'})
Output:
nikhilaggarwal3
kumar_satyam
Picked
R Error-handling
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming