R On Exit
on.exit sets code that runs when a function leaves. The set code runs after the body, however the function ends.
Cleanup after the body
work sets its cleanup with on.exit and then prints its body line. The cleanup line prints after the body line.
work <- function() {
on.exit(cat("cleaning up\n"))
cat("working\n")
}
work()Cleanup on an early return
check returns early for a negative score. The closing line still prints before each returned value is printed.
check <- function(score) {
on.exit(cat("closing\n"))
if (score < 0) {
return("invalid")
}
return("valid")
}
print(check(-1))
print(check(5))A second handler replaces the first
replace sets two handlers and the second call leaves add out. Only the second handler runs after the body.
replace <- function() {
on.exit(cat("first set\n"))
on.exit(cat("second set\n"))
cat("body\n")
}
replace()Stack handlers with add
setup sets two handlers and the second call passes add = TRUE. Both handlers run after the body, in the order they were set.
setup <- function() {
on.exit(cat("first set\n"))
on.exit(cat("second set\n"), add = TRUE)
cat("body\n")
}
setup()Example
open_report <- function(name) {
on.exit(cat("report closed\n"))
on.exit(cat("log written\n"), add = TRUE)
cat("reading\n")
print(nchar(name))
}
open_report("sales")Key points
- on.exit takes the cleanup code for the current function.
- The cleanup code runs after the body finishes.
- The cleanup code also runs when return ends the function early.
- A second on.exit call replaces the first handler.
- With add = TRUE, a second handler stacks behind the first one instead.
- Stacked handlers run in the order they were set.
In this example, the body reads the report name and prints its length first. The two stacked handlers then run in the order they were set, closing the report before writing the log.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
A function sets two on.exit handlers, and the second call uses add = TRUE. When do the handlers run?