Errors in R Programming Language

In R, error handling is typically done through the use of conditions and tryCatch blocks. While R doesn’t have a built-in error type like some other languages, we can create custom error objects and use them in a similar way.

library(stringr)

# Function that may produce an error
f <- function(arg) {
  if (arg == 42) {
    # In R, we use stop() to signal errors
    stop("can't work with 42")
  }
  # Return a list to mimic multiple return values
  list(result = arg + 3, error = NULL)
}

# Custom error objects
ErrOutOfTea <- simpleError("no more tea available")
ErrPower <- simpleError("can't boil water")

# Function that uses custom errors
makeTea <- function(arg) {
  if (arg == 2) {
    return(ErrOutOfTea)
  } else if (arg == 4) {
    # To wrap errors in R, we can create a new error with the original as the cause
    return(simpleError(str_c("making tea: ", ErrPower$message), call = NULL))
  }
  NULL
}

# Main execution
main <- function() {
  for (i in c(7, 42)) {
    # In R, we use tryCatch for error handling
    result <- tryCatch({
      f(i)
    }, error = function(e) {
      cat("f failed:", conditionMessage(e), "\n")
      return(NULL)
    })
    
    if (!is.null(result)) {
      cat("f worked:", result$result, "\n")
    }
  }
  
  for (i in 0:4) {
    err <- makeTea(i)
    if (!is.null(err)) {
      # In R, we can check the class of the error or its message
      if (identical(err, ErrOutOfTea)) {
        cat("We should buy new tea!\n")
      } else if (str_detect(err$message, ErrPower$message)) {
        cat("Now it is dark.\n")
      } else {
        cat("unknown error:", conditionMessage(err), "\n")
      }
      next
    }
    cat("Tea is ready!\n")
  }
}

main()

In this R translation:

  1. We use stop() to signal errors, which is similar to returning an error in other languages.

  2. Custom errors are created using simpleError().

  3. To mimic multiple return values, we return a list with result and error fields.

  4. Error handling is done using tryCatch() blocks, which is similar to try-catch in other languages.

  5. We use identical() to check for specific errors, and str_detect() to check for wrapped errors.

  6. The cat() function is used for console output, similar to fmt.Println() in the original code.

When you run this script, you should see output similar to:

f worked: 10 
f failed: can't work with 42 
Tea is ready!
Tea is ready!
We should buy new tea!
Tea is ready!
Now it is dark.

This R code demonstrates error handling, custom errors, and error checking, adapting the concepts from the original code to R’s idioms and conventions.