Defensive R: Validation, Conditions and Checks
Validate data before analysing it, raise errors and warnings, write custom conditions, handle problems with tryCatch and withCallingHandlers, use on.exit, and see the real exit status of a script that stops.
In this lesson you will
- Validate input with clear messages
- Raise and handle errors and warnings
- Create a custom condition class
- Know what a failing script returns
About 28 minutes
When the data are wrong
Nia’s code is used by other teachers now, and their files are not always right: a column is missing, a height is negative, a group name is misspelled. An analysis that prints an answer for bad data is worse than one that stops, because the wrong answer looks real. Defensive programming means checking assumptions at the start, failing early with a message that says what is wrong and where, and cleaning up after yourself even when something fails. R’s condition system has three levels: a message is information, a warning says that something may be wrong but the code can continue, and an error stops the code unless somebody handles it.
stop raises an error, warning raises a warning, and stopifnot checks a list of conditions and stops at the first false one, with an automatic message. tryCatch runs code and handles a condition by unwinding the call, so that the code after the problem does not run, and its finally clause runs in every case. withCallingHandlers handles a condition without unwinding: the code continues after the handler, which makes it right for collecting every warning. A custom condition is created with structure and a class vector, so that code can handle exactly the problems it understands. At the top level of a script, an unhandled error prints “Error:”, then “Execution halted”, and Rscript exits with a non-zero status, which is what a scheduler or a shell script can test.
| Tool | Use |
|---|---|
| stopifnot(cond) | Check assumptions |
| stop(“msg”) | Raise an error |
| warning(“msg”) | Raise a warning |
| tryCatch(expr, error = f, finally = g) | Handle and clean up |
| withCallingHandlers(expr, warning = f) | Observe and continue |
| on.exit(expr) | Run cleanup when the function ends |
validate <- function(d) {
stopifnot(is.data.frame(d))
need <- c("group", "height")
missing_cols <- setdiff(need, names(d))
if (length(missing_cols) > 0) stop("missing columns: ", paste(missing_cols, collapse = ", "))
bad <- which(is.na(d$height) | d$height <= 0)
if (length(bad) > 0) warning("rows with a bad height: ", paste(bad, collapse = ", "))
d[-bad, ]
}
data_error <- function(msg) structure(class = c("dataError", "error", "condition"), list(message = msg, call = NULL))
good <- data.frame(group = c("a", "b", "a", "b"), height = c(12.1, 15.3, -2, NA))
caught <- character(0)
clean <- withCallingHandlers(validate(good), warning = function(w) { caught <<- c(caught, conditionMessage(w)); invokeRestart("muffleWarning") })
cat("rows kept:", nrow(clean), "| warnings collected:", length(caught), "|", caught, "\n")
r1 <- tryCatch(validate(data.frame(group = "a")), error = function(e) paste("error:", conditionMessage(e)))
cat(r1, "\n")
r2 <- tryCatch(validate(list(1, 2)), error = function(e) paste("error:", conditionMessage(e)))
cat(r2, "\n")
r3 <- tryCatch(stop(data_error("group names must be lowercase")), dataError = function(e) paste("custom condition:", conditionMessage(e), "| classes:", paste(class(e), collapse = " ")))
cat(r3, "\n")
log <- character(0)
work <- function(fail) {
on.exit(log <<- c(log, "cleanup ran"))
log <<- c(log, "started")
if (fail) stop("something broke")
"finished"
}
res <- tryCatch(work(TRUE), error = function(e) "recovered", finally = log <- c(log, "finally ran"))
cat("result:", res, "| log:", paste(log, collapse = " > "), "\n")
ok <- tryCatch(work(FALSE), error = function(e) "recovered")
cat("second call:", ok, "\n")
cat("conditions: warning is", class(simpleWarning("x"))[1], "| error is", class(simpleError("x"))[1], "\n")
rows kept: 2 | warnings collected: 1 | rows with a bad height: 3, 4
error: missing columns: height
error: is.data.frame(d) is not TRUE
custom condition: group names must be lowercase | classes: dataError error condition
result: recovered | log: started > cleanup ran > finally ran
second call: finished
conditions: warning is simpleWarning | error is simpleError
cat("analysis starting\n")
d <- data.frame(group = c("a", "b"), height = c(12.1, 15.3))
stopifnot(nrow(d) >= 3)
cat("this line is never reached\n")
analysis starting
Error: nrow(d) >= 3 is not TRUE
Execution halted
The validation function tested the data in order of seriousness. For a table with a negative height and a missing height, it did not stop but raised one warning, “rows with a bad height: 3, 4”, and returned the 2 usable rows. The warning was collected with withCallingHandlers, which recorded the message (1 warning in all) and called the restart muffleWarning, so that the code continued and the message did not appear again at the end. A table without the height column cannot be analysed, so that is an error: the message names exactly what is missing, “error: missing columns: height”, and the check on the input type, a list instead of a data frame, produced “error: is.data.frame(d) is not TRUE” from stopifnot, with no message to write.
The custom condition has the class vector dataError error condition, so that tryCatch(…, dataError = …) handles only this kind of problem and lets every other error through, and its message is “group names must be lowercase”. The cleanup example shows the order of events when a function fails: the function started, its on.exit handler ran, as it does whether the function succeeds or not, and then the finally clause ran, all recorded in the log as “started > cleanup ran > finally ran”, while the caller received “recovered”. When the function succeeded, it returned “finished”.
The second program has no handler at all, to show what happens at the top level of a script. The line before the check printed, the stopifnot failed, and R printed the error message and “Execution halted”, and the line after it never ran. The exit status of the process was 1, which can be tested in a shell with the status variable, so that a scheduled job can tell the difference between “done” and “failed”:
exit status: 1
Independent check: Python applied the same validation to the same four rows, keeping the rows with a positive known height, and found two usable rows and the bad row numbers 3 and 4, exactly as R’s warning reported. The error messages and the condition classes are R specific, so for them the check is the real output of the run.
Check by hand: the table has four rows, 12.1 and 15.3 are fine, -2 is not positive, and NA is unknown, so rows 3 and 4 are bad and two are kept. The order in the log is started (the first line of the function), cleanup ran (when the function exits, by error), and finally ran (when tryCatch leaves).
tryCatch(expr, error = function(e) NULL) hides every failure, including bugs in your own code. Handle specific classes of conditions, log the message, and let unexpected ones stop the script.
A message such as “missing columns: height” tells the user what to fix. A message such as “subscript out of bounds”, ten steps later, does not. Validate the input at the beginning of each script.
Every program in this lesson was run with R 4.3.3 using Rscript –vanilla (base R only, no packages) while the course was written. R releases new versions every year, so check r-project.org for the current version and for any change in behaviour. The exit status was recorded from the real run of the failing script.
Practice
Extend validate so that group names with capital letters raise your custom dataError. Collect all the problems in a list and report them together, rather than stopping at the first. Write a script that runs the analysis and exits with a status of 2 using quit(status = 2) when validation fails.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does stopifnot do?
- Prints a warning
- Loops
- Stops with an automatic message if a condition is not TRUE
- Loads a package
A concise way to check assumptions.
What is the difference between tryCatch and withCallingHandlers?
- They are the same
- tryCatch unwinds the call, calling handlers let the code continue
- tryCatch is for warnings only
- Calling handlers stop the code
Use calling handlers to collect warnings.
When does on.exit run?
- Only at success
- When the function ends, normally or by error
- Only at errors
- Never
It is the place for cleanup.
What does Rscript return for an unhandled error?
- A non-zero exit status
- 0
- A warning
- Nothing
Here the status was 1.
Why define a custom condition class?
- So that code can handle exactly that problem
- To make errors faster
- It is required
- To hide errors
Class-specific handlers.
Summary
- Validate input early and fail with a clear message.
- stop, warning and message are the three levels of condition.
- tryCatch handles and unwinds, withCallingHandlers observes and continues.
- An unhandled error ends Rscript with a non-zero exit status.
Questions
Should I use warnings or errors for bad data?
Use an error when the analysis cannot give a meaningful answer, and a warning when you can continue safely, such as after dropping a few rows that you report.
How do I show a message that is not an error?
Use message(), which goes to the error stream, so it does not mix with printed results, and can be silenced with suppressMessages().
What is traceback()?
A function that shows the call stack of the last error in an interactive session. In a script, use tryCatch with sys.calls or options(error = ...), and check the documentation.
