tryCatch2 {this.path} | R Documentation |
A variant of tryCatch
that accepts an else.
argument,
similar to try except
in ‘Python’.
tryCatch2(expr, ..., else., finally)
expr |
expression to be evaluated. |
... |
condition handlers. |
else. |
expression to be evaluated if evaluating |
finally |
expression to be evaluated before returning or exiting. |
The use of the else.
argument is better than adding additional code to
expr
because it avoids accidentally catching a condition that wasn't
being protected by the tryCatch
call.
FILES <- tempfile(c("existent-file_", "non-existent-file_"))
writeLines("line1\nline2", FILES[[1L]])
for (FILE in FILES) {
con <- file(FILE)
tryCatch2({
open(con, "r")
}, condition = function(cond) {
cat("cannot open", FILE, "\n")
}, else. = {
cat(FILE, "has", length(readLines(con)), "lines\n")
}, finally = {
close(con)
})
}
unlink(FILES)