calling source()
for non-existing file generates both error
and warning
:
source('nofile.R')
# Error in file(filename, "r", encoding = encoding) :
# cannot open the connection
# In addition: Warning message:
# In file(filename, "r", encoding = encoding) :
# cannot open file 'nofile.R': No such file or directory
I tried to catch the error in tryCatch()
:
trysource <- function(src.file){
result <- tryCatch(
expr = {source(src.file);},
error = function(e){cat('My error: ', e$message, '\n');},
finally = cat("finished.\n")
);
}
trysource('nofile.R')
# My error: cannot open the connection
# finished.
# Warning message:
# In file(filename, "r", encoding = encoding) :
# cannot open file 'nofile.R': No such file or directory
as you see, it catches the error successfully. Then I added warning=
part:
trysource <- function(src.file){
result <- tryCatch(
expr = {source(src.file);},
error = function(e){cat('My error: ', e$message, '\n');},
warning = function(w){cat('My warning: ', w$message, '\n');},
finally = cat("finished.\n")
);
}
trysource('nofile.R')
# My warning: cannot open file 'nofile.R': No such file or directory
# finished.
Now it catches the warning but ignores the error! Can anyone explain why it happens and if there is any way to catch both?