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)
Run the code above in your browser using DataLab