Library contents

R tryCatch and stop

tryCatch can convert a signaled error into a fallback value for one calculation. Other elements in the batch can then be processed.

A simple example

tryCatch and stop

  1. Start with An expression signals an error
  2. Do this Catch it and return 0
  3. Result 0
The handler supplies a result, so the surrounding calculation can continue.

Syntax

R syntax
tryCatch(expression, error = function(condition) fallback)
Run this example in R

Save the program as Lesson.R. Use R 4.x.

Rscript --vanilla Lesson.R

Recover from a failed validation in a batch

A batch processor must distinguish an anticipated input problem from a different failure. Examine the operation's error information before deciding whether to skip one record, report the cause or stop.

From the programcat(paste(values, collapse = " "), "\n", sep = "")
Result3 NA 5
Lesson.R
root <- function(x) {
  if (x < 0) stop("negative reading")
  sqrt(x)
}
values <- vapply(c(9, -1, 25), function(x) {
  tryCatch(root(x), error = function(e) NA_real_)
}, numeric(1))
cat(paste(values, collapse = " "), "\n", sep = "")
Output
3 NA 5

Return the same type from the normal path and the error handler. NA_real_ makes a failed reading visible while keeping the collected result numeric.

R documentation for tryCatch and stop

Advertisements

Split a studio hire fee

Two groups register for a 24-credit rehearsal. Divide the total among the registered groups using whole-number division. The desk puts the batch on hold if the divisor is zero.

Given24 credits / 2 groups
Worked resultShare calculated

Hold an empty field-trip batch

A trip has a 30-credit fixed fee and no groups registered yet. Divide the total among the registered groups using whole-number division. The desk puts the batch on hold if the divisor is zero.

Given30 credits / 0 groups
Worked resultHold batch