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
- Start with An expression signals an error
- Do this Catch it and return 0
- Result 0
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.
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 = "")
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
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.
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.