| tryCatch2 | R Documentation |
Variants of \codelink3base:conditionstryCatch() 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.condition
expr |
expression to be evaluated. |
... |
for Arguments which are missing will use the next non-missing argument. If
there is no next non-missing argument, |
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 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)
# })
}
unlink(FILES)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.