如何捕获`file()`调用的错误和警告?

时间:2016-01-15 16:56:46

标签: r

为不存在的文件调用source()会同时生成errorwarning

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

我试图抓住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

如您所见,它成功捕获错误。然后我添加了warning=部分:

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.

现在它捕获警告但忽略了错误!任何人都可以解释为什么会发生这种情况,是否有办法同时捕捉到它们?

0 个答案:

没有答案