Learn R Programming

this.path (version 1.4.0)

tryCatch2: Condition Handling and Recovery

Description

A variant of tryCatch() that accepts an else. argument, similar to try except in ‘Python’.

Usage

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

Arguments

expr

expression to be evaluated.

...

condition handlers.

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

Run this code
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)

Run the code above in your browser using DataLab