tryCatch2: Condition Handling and Recovery

tryCatch2R Documentation

Condition Handling and Recovery

Description

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().

Usage

tryCatch2(expr, ..., else., finally)
tryCatch3(expr, ..., else., finally)

last.condition

Arguments

expr

expression 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.

else.

expression to be evaluated if evaluating expr does not throw an error nor a condition is caught.

finally

expression to be evaluated before returning or exiting.

Details

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.

Examples

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)

ArcadeAntics/this.path documentation built on July 27, 2024, 12:05 a.m.