tryCatch2.RdVariants of tryCatch() that accept an
else. argument, similar to try except in ‘Python’.
last.condition will be the last thrown and caught condition in
tryCatch3().
tryCatch2(expr, ..., else., finally)
tryCatch3(expr, ..., else., finally)
last.conditionexpression to be evaluated.
for tryCatch2(), condition handlers. for
tryCatch3(), expressions to be conditionally evaluated.
Arguments which are missing will use the next non-missing argument. If
there is no next non-missing argument, NULL will be returned
invisibly.
expression to be evaluated if evaluating expr does not
throw an error nor a condition is caught.
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 was not
being protected by the tryCatch() call.
FILES <- tempfile(c("existent-file_", "non-existent-file_"))
writeLines("line1\nline2", FILES[[1L]])
for (FILE in FILES) {
conn <- file(FILE)
tryCatch2({
open(conn, "r")
}, condition = function(cond) {
cat("cannot open", FILE, "\n")
}, else. = {
cat(FILE, "has", length(readLines(conn)), "lines\n")
}, finally = {
close(conn)
})
# ## or more naturely with tryCatch3:
# tryCatch3({
# open(conn, "r")
# }, condition = {
# cat("cannot open", FILE, "\n")
# }, else. = {
# cat(FILE, "has", length(readLines(conn)), "lines\n")
# }, finally = {
# close(conn)
# })
}
#> /tmp/RtmppDjC0Z/existent-file_4b0c23e5c144b has 2 lines
#> cannot open /tmp/RtmppDjC0Z/non-existent-file_4b0c2492afc4d
unlink(FILES)