R / CHAPTER 12
Conditions and reliable cleanup
AdvancedRecover narrowly and restore temporary state.
By the end of this chapter
- Handle expected errors separately from warnings
- Register cleanup with on.exit
- Avoid silently replacing failed results
The idea
R conditions distinguish errors, warnings, and other signals. An error stops the current computation unless handled; a warning may allow a value to be returned. Use tryCatch where a layer knows how to report or recover from a failure, and keep its protected operation narrow. Returning zero for every error can turn a broken computation into apparently valid data.
A function that temporarily changes options or opens a resource owns the obligation to restore or close it. Register cleanup with on.exit immediately after acquisition, using add=TRUE when several cleanup actions must be retained. The cleanup runs when the function exits normally or through an error. Tests should inspect both the return path and failure path, including whether temporary state was restored.
demo <- function() {
on.exit(cat("cleanup\n"), add=TRUE)
stop("bad input")
}
result <- tryCatch(demo(),error=function(e) "handled")
cat(result,"\n",sep="")cleanup handled
The function’s exit handler runs as the error leaves demo, then the outer error handler supplies its recovery value.
Try it yourself
Temporarily change one option inside a function and restore it even when a calculation fails.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING