R 中的函数和 try() [英] Functions and try() in R
问题描述
仍然在用 R 苦苦挣扎,尤其是在错误处理方面:
Still struggling with R, especially with error handling:
如果我使用:
result <- try(sqlSave(ch,df,tablename="tblTest"))
我可以使用:
if (class(result) != "try-error")
检查是否有问题.没问题.
to check if something went wrong. No problem.
但是如果我将 try
与一个函数结合使用,它就不会像我预期的那样工作:
But if I use try
in combination with a function it doesn't work as I expected:
result <- try(ch<-odbcConnect("TEST"))
为 result
提供-1",为 class(result)
gives "-1" for result
and "integer" for class(result)
那我应该用吗
ch<-odbcConnect("TEST")
if (ch != -1)
并使用 geterrmessage()
作为错误信息?
and use geterrmessage()
for the error message?
推荐答案
如果您仔细阅读错误消息,您可能会看到 odbcConnect
向您发出警告.错误是由 ODBC 驱动程序生成的,它不是 try
中的错误,意思是(geterrmessage()
也不起作用).
If you read closely error message you could see that odbcConnect
gives you warning. Error is generated by ODBC drivers and it isn't error in try
meaning (geterrmessage()
won't work either).
您可以使用 tryCatch
来处理此问题,例如:
You could use tryCatch
to handle this, e.g.:
tryCatch(odbcConnect("TEST"), warning=function(w) print("FAIL!"))
<小时>
更多解释:
-1 是 odbcDriverConnect
函数的结果.如果你看代码有几行
Some more explanation:
-1 is a result of odbcDriverConnect
function. If you look at the code there are lines
stat <- .Call(C_RODBCDriverConnect, as.character(connection),
id, as.integer(believeNRows), as.logical(readOnlyOptimize))
if (stat < 0L) {
warning("ODBC connection failed")
return(stat)
}
所以你结束时没有错误(并有警告)和来自 C 级的整数代码.实际上,当连接成功时也会返回此代码(但随后等于 1).当没有错误时,结果类不能是try-error
.try
和函数不是问题,而是特定于这个特定函数 (odbcDriverConnect
).
So you end without errors (and with a warning) and with integer code from C-level. Actually this code is returned when connection is succeed too (but then is equal 1). When there is no errors then result class can't be try-error
.
It is not problem with try
and functions but specific of this particular function (odbcDriverConnect
).
你当然可以在你的例子中使用这种行为
You could of course use this behaviour as in your example
ch <- odbcConnect("TEST")
if (ch != -1)
使用 tryCatch
你可以做到
tryCatch(ch<-odbcConnect("TEST"), warning=function(w) print("FAIL!"))
它在成功时创建 ch
变量并在失败时打印消息.
或者
which creates ch
variable when succeed and print message when failed.
Or
ch <- tryCatch(odbcConnect("TEST"), warning=function(w) {print("FAIL!");return(NA)})
它总是创建 ch
变量,但在失败的情况下有 NA
值.
which always creates ch
variable but in case of failure there is NA
value.
这篇关于R 中的函数和 try()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!