🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

R Error Handling — tryCatch and Debugging

R BasicsError Handling🟢 Free Lesson

R Error Handling — tryCatch and Debugging

Learning Objectives

By the end of this tutorial, you will be able to:

  • Handle errors gracefully with tryCatch() and try()
  • Catch and manage warnings
  • Create custom error conditions
  • Use debugging tools like browser(), debug(), and traceback()
  • Write robust functions that handle edge cases

Error Handling Basics

try() — Simple Error Handling

# try() returns error message instead of stopping
result <- try(log("a"))
# Error in log("a") : non-numeric argument to mathematical function
class(result)   # [1] "try-error"

# Check for error
if (inherits(result, "try-error")) {
  cat("An error occurred\n")
}

# With silent = TRUE
result <- try(log("a"), silent = TRUE)

tryCatch() — Advanced Error Handling

# tryCatch with different handlers
result <- tryCatch(
  {
    log("a")
  },
  error = function(e) {
    cat("Error:", conditionMessage(e), "\n")
    NA
  },
  warning = function(w) {
    cat("Warning:", conditionMessage(w), "\n")
    NULL
  }
)
# Error: non-numeric argument to mathematical function

# Handle specific error types
result <- tryCatch(
  {
    x <- 1
    y <- "2"
    x + y
  },
  error = function(e) {
    if (grepl("non-numeric", conditionMessage(e))) {
      cat("Type error caught\n")
      NA
    } else {
      stop(e)  # Re-throw unknown errors
    }
  }
)

Warning Handling

# Catch warnings
result <- withCallingHandlers(
  {
    x <- log(-1)  # Produces warning
    x
  },
  warning = function(w) {
    cat("Warning caught:", conditionMessage(w), "\n")
    invokeRestart("muffleWarning")  # Suppress warning
  }
)

# Suppress warnings
result <- suppressWarnings(log(-1))

# withCallingHandlers vs tryCatch
# withCallingHandlers: continues after handler
# tryCatch: exits the expression after handler

Custom Error Conditions

# Create custom error
validate_age <- function(age) {
  if (!is.numeric(age)) {
    stop("Age must be numeric", call. = FALSE)
  }
  if (age < 0 || age > 150) {
    stop(paste("Age must be between 0 and 150, got:", age), call. = FALSE)
  }
  age
}

# Custom error class
invalid_input <- function(message) {
  structure(
    class = c("invalid_input", "error", "condition"),
    list(message = message)
  )
}

safe_divide <- function(a, b) {
  if (b == 0) {
    stop(invalid_input("Cannot divide by zero"))
  }
  a / b
}

# Handle custom errors
tryCatch(
  safe_divide(10, 0),
  invalid_input = function(e) {
    cat("Invalid input:", e$message, "\n")
    NA
  }
)

Debugging Tools

browser() — Interactive Debugging

my_function <- function(x) {
  browser()  # Execution stops here
  y <- x^2
  z <- y + 1
  return(z)
}

my_function(5)
# Called from: my_function(5)
# Browse[1]>
# Type n (next), c (continue), q (quit), s (step into)

debug() and undebug()

# Debug a function
debug(my_function)
my_function(5)  # Enters debug mode

# Step through
undebug(my_function)

# Debug once
debugonce(my_function)

traceback() and options(error = traceback)

# Show call stack after error
f <- function(x) g(x)
g <- function(x) h(x)
h <- function(x) x + "error"

tryCatch(f(1), error = function(e) traceback())

# Auto-show traceback on error
options(error = traceback)

Common Error Patterns

# Validate input
safe_mean <- function(x, na.rm = FALSE) {
  if (!is.numeric(x)) {
    stop("x must be numeric")
  }
  if (length(x) == 0) {
    stop("x must not be empty")
  }
  mean(x, na.rm = na.rm)
}

# Handle missing values
safe_log <- function(x) {
  if (any(x <= 0)) {
    warning("Non-positive values replaced with NA")
    x[x <= 0] <- NA
  }
  log(x)
}

# Retry pattern
retry <- function(expr, max_attempts = 3) {
  for (i in 1:max_attempts) {
    result <- tryCatch(
      expr,
      error = function(e) NULL
    )
    if (!is.null(result)) return(result)
    cat("Attempt", i, "failed, retrying...\n")
  }
  stop("All attempts failed")
}

Practice Exercises

Exercise 1: Safe Calculator

Write a calculator function that handles division by zero, non-numeric inputs, and returns meaningful error messages.

Solution

safe_calculator <- function(a, b, op) {
  if (!is.numeric(a) || !is.numeric(b)) {
    stop("Inputs must be numeric")
  }

  switch(op,
    add = a + b,
    subtract = a - b,
    multiply = a * b,
    divide = {
      if (b == 0) {
        stop("Cannot divide by zero")
      }
      a / b
    },
    stop(paste("Unknown operation:", op))
  )
}

safe_calculator(10, 5, "divide")     # [1] 2
safe_calculator(10, 0, "divide")     # Error: Cannot divide by zero
safe_calculator("a", 5, "add")       # Error: Inputs must be numeric

Key Takeaways

  • try() is simple — returns try-error on failure
  • tryCatch() is flexible — separate handlers for errors, warnings, messages
  • withCallingHandlers() handles warnings without stopping
  • Custom conditions let you create domain-specific errors
  • browser() pauses execution for interactive debugging
  • debug() steps through a function line by line
  • traceback() shows the call stack after an error
  • Always validate inputs at the start of functions

Next: Learn about R Packages — extending R's functionality.


Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement