Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

How does one "throw" an error in R? I have a function that takes a data frame and some column names and does stuff with them. If the columns don't exist, I want the function to stop and to stop all functions depending on it.

I have looked at recover and browse and traceback but, well, they seemed to be close but not what I am looking for.

1 Answer

0 votes
by

You can use the trycatch function from the base package that provides a mechanism for handling unusual conditions, including errors and warnings.

The basic syntax for trycatch is as follows:

tryCatch(expr, ..., finally)

expr

expression to be evaluated.

finally

expression to be evaluated before returning or exiting.

...

additional arguments

The condition system provides a mechanism for signaling and handling unusual conditions, including errors and warnings. Conditions are represented as objects that contain information about the condition that occurred, such as a message and the call in which the condition occurred.

For example:

With the try function you can handle errors to continue the execution (by ignoring the error):

try(log("not a number"), silent = TRUE)

print("Don’t Stop the Execution")

To check for a condition:

tryCatch( { result <- log(-1); print(result) }

          , warning = function(w) { print("A warning message") })

Output:

[1] "A warning message"

Conditions are signaled by 'signalCondition'. In addition, the 'stop' and 'warning' functions have been modified to also accept condition arguments.

To know more about conditional handling and recovery go to the man page pf trycatch as follows:

?tryCatch

Browse Categories

...