Error handling in R: try-catch statements, assertions

In R, you can handle errors and exceptions using try-catch statements and assertions.

## Try-catch statements
# Define a function that may generate an error
divide <- function(x, y) { if (y == 0) { stop("Cannot divide by zero") } return(x / y) } # Use a try-catch statement to catch the error x <- 10 y <- 0 tryCatch({ result <- divide(x, y) print(result) }, error = function(e) { print(paste("Error:", e$message)) }) In this code, we define a function called `divide()` that takes two arguments, `x` and `y`, and returns the result of `x` divided by `y`. If `y` is equal to zero, the function throws an error with the `stop()` function. We then use a try-catch statement to call the `divide()` function with arguments `x = 10` and `y = 0`. The `tryCatch()` function captures any errors that occur inside its block and executes the error function, which we define to print the error message with `e$message`. ## Assertions # Define a function that uses an assertion square_root <- function(x) { assert(x >= 0, “x must be non-negative”)
return(sqrt(x))
}

# Use the function with a valid input
x <- 9 result <- square_root(x) print(result) # Use the function with an invalid input x <- -9 result <- square_root(x) print(result) In this code, we define a function called `square_root()` that takes a single argument, `x`, and returns the square root of `x`. We use the `assert()` function to check that `x` is non-negative. If `x` is negative, the function throws an error with a message. We then use the function with a valid input (`x = 9`) and print the result. We also use the function with an invalid input (`x = -9`), which triggers an assertion error and stops the execution of the function. Note that you can also use other error handling techniques in R, such as the `stop()` and `warning()` functions, and various debugging tools, such as the `traceback()` function and the `debug()` function. You can find more information on these techniques in the R documentation or online tutorials and resources.