EZ

Eduzan

Learning Hub

Eduzan
Eduzan / R (programming language)

Error Handling in R Programming

Computer Science / R (programming language) tutorial chapter - Published 2025-12-13 - R (programming language)

Error handling is the process of dealing with unexpected or anomalous errors that could cause a program to terminate abnormally during execution. In R, error handling can be implemented in two main ways:

  1. Directly invoking functions like stop() or warning().
  2. Using error options such as warn or warning.expression.

Key Functions for Error Handling

  1. stop(...): This function halts the current operation and generates a message. The control is returned to the top level.
  2. warning(...): Its behavior depends on the value of the warn option:
    • If warn < 0, warnings are ignored.
    • If warn = 0, warnings are stored and displayed after execution.
    • If warn = 1, warnings are printed immediately.
    • If warn = 2, warnings are treated as errors.
  3. tryCatch(...): Allows evaluating code and managing exceptions effectively.

Handling Conditions in R

When unexpected errors occur during execution, it’s essential to debug them interactively. However, there are cases where errors are anticipated, such as model fitting failures. To handle such situations in R, three methods can be used:

  1. try(): Enables the program to continue execution even after encountering an error.
  2. tryCatch(): Manages conditions and defines specific actions based on the condition.
  3. withCallingHandlers(): Similar to tryCatch(), but handles conditions with local handlers instead of exiting ones.

Example: Using tryCatch() in R

Here’s an example demonstrating how to handle errors, warnings, and final cleanup using tryCatch().

# Using tryCatch for error handling
tryCatch(
  expr = {
    log(10) # Evaluates the logarithm
    print("Calculation successful.")
  },
  error = function(e) {
    print("An error occurred.")
  },
  warning = function(w) {
    print("A warning was encountered.")
  },
  finally = {
    print("Cleanup completed.")
  }
)

Output:

[1] "Calculation successful."
[1] "Cleanup completed."

Example: Using withCallingHandlers() in R

The withCallingHandlers() function handles conditions using local handlers. Here’s an example:

# Using withCallingHandlers for condition handling
evaluate_expression <- function(expr) {
  withCallingHandlers(
    expr,
    warning = function(w) {
      message("Warning encountered:\n", w)
    },
    error = function(e) {
      message("Error occurred:\n", e)
    },
    finally = {
      message("Execution completed.")
    }
  )
}

# Test cases
evaluate_expression({10 / 5})  # Normal operation
evaluate_expression({10 / 0})  # Division by zero
evaluate_expression({"abc" + 1})  # Invalid operation

Example:

Warning encountered:
Execution completed.

Error occurred:
Execution completed.

Error occurred:
Execution completed.
End of lesson.