Dai*_*ail 8 error-handling r try-catch
我getYahooData()在TTR包中使用功能非常强烈.
我有这段代码:
for(i in 1:nrow(symbol)){
tryCatch(prices <- getYahooData(symbol$symbol[i], from, to, freq="daily",
type="price"),
warning=function(e) continue <- 0)
if (continue==0) next
}
Run Code Online (Sandbox Code Playgroud)
这个循环很长我得到这个错误:
文件错误(文件,"rt"):所有连接都在使用中调用:tryCatch ... doTryCatch - > getYahooData - > getYahooData - > read.table - > file执行暂停
我能做什么?
更新:
如果我使用closeAllConnections(),我得到:
I get: *** caught segfault *** address (nil), cause 'memory not mapped' Traceback: 1: getConnection(set[i]) 2: close(getConnection(set[i])) 3: closeAllConnections() aborting ...
Run Code Online (Sandbox Code Playgroud)
Jor*_*eys 15
第一:永远不要在你的生活中继续使用继续构建.这是没用的.如果您为错误或警告定义了处理程序,tryCatch() 则会继续.它将使用那个而不是"默认" error=function(e) stop(e).这个将停止你的功能.如果你定义一个处理程序(无论是warning=或error=),你的脚本将不会停止,因此继续是没有必要的.
这说:在这种情况下正确使用tryCatch将是:
for(i in 1:nrow(symbol)){
tryCatch(prices <- getYahooData(symbol$symbol[i], from, to, freq="daily",
type="price"), error = function(e){})
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您在脚本中使用它并希望在发生错误时转到下一个循环,您可以简单地使用:
for(i in 1:nrow(symbol)){
prices <- try(getYahooData(symbol$symbol[i], from, to, freq="daily",
type="price"), silent=TRUE)
if(inherits(prices,"try-error")) { next } # only true if an error occurs
... # rest of calculations
}
Run Code Online (Sandbox Code Playgroud)
如果您使用过tryCatch这种方式或尝试过,那么您就不会遇到此处报告的问题.
如果我使用不存在的符号,现在我可以重现你的情况.您错误地使用tryCatch()功能会给您带来麻烦.read.table返回错误(Error in file(file, "rt") : cannot open the connection).这是一个错误,而不是警告.您会收到另一个警告,指出未找到404文件.
当警告与错误一起发出时,首先处理警告的处理函数.那是因为在停止函数之前必须抛出警告.因此,它不会处理你的错误,这意味着由于未处理错误,因此连接注册出错.由于无法打开连接,因此on.exit(close(file))在read.table()不被调用.因此,连接没有正确关闭并且仍被认为是开放的,尽管R不再能找到它(showAllConnections()什么也没有显示).on.exit(close(...))无效.showConnections()没有显示连接,但不知何故R仍然认为它在那里.因此,所有的地狱都会破裂而你会崩溃.
感谢@Tommy的更正
一个简单的代码示例来说明这一点:
myfun <- function(x){
if(x>1) warning("aWarning")
stop("aStop")
x
}
tryCatch(myfun(0.5),
warning=function(w)print("warning"),
error=function(e) print("stop"))
[1] "stop"
tryCatch(myfun(1.5),
warning=function(w)print("warning"),
error=function(e) print("stop"))
[1] "warning"
Run Code Online (Sandbox Code Playgroud)
综上所述 :
并且作为额外的:你的循环只会返回最后一次调用的结果,因为你prices每次进行循环时都会覆盖,以防你使用正确的符号.
编辑:如果您想继续操作
42-*_*42- 10
关闭一些连接?可以像closeAllConnections()在循环体的末尾插入一样简单.
小智 8
这确实是R源代码中有关如何注册连接的错误.我在R Bugzilla网站上发布了一些评论和补丁:http://bugs.r-project.org/bugzilla3/show_bug.cgi?id = 14660.Joris的建议是合理的.但是,当修复错误时,closeAllConnections()也将起作用.(PS这是我的第一篇StackOverflow帖子.如果我违反了礼仪,请原谅我.)