tryCatch2 {this.path}R Documentation

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 wasn't being protected by the tryCatch call.

Examples

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)

[Package this.path version 0.11.0 Index]