This is an old question but there is no a clean solution yet. This probably is not answering this specific question, but those looking for answers on 'how to gracefully exit from an R script' will probably land here. It seems that R developers forgot to implement an exit() function. Anyway, the trick I've found is:
continue <- TRUE
tryCatch({
# You do something here that needs to exit gracefully without error.
...
# We now say bye-bye
stop("exit")
}, error = function(e) {
if (e$message != "exit") {
# Your error message goes here. E.g.
stop(e)
}
continue <<-FALSE
})
if (continue) {
# Your code continues here
...
}
cat("done.\n")
Basically, you use a flag to indicate the continuation or not of a specified block of code. Then you use the stop()
function to pass a customized message to the error handler of a tryCatch()
function. If the error handler receives your message to exit gracefully, then it just ignores the error and set the continuation flag to FALSE
.