【发布时间】:2016-07-20 13:39:14
【问题描述】:
考虑以下代码:
test1 <- "a"
test2 <- "a"
tryCatch(stop(), error= function(err){
print(test1)
print(test2)
test1 <- "b"
test2 <<- "b"
})
结果:
print(test1)
[1] "a"
print(test2)
[1] "b"
变量test1的值在tryCatch块内是可见的,但是用“
如果用
在 tryCatch 块中使用
编辑:根据 Bernhard 的回答,以下代码是否弥补了解决此问题的正确方法?
test1 <- "a"
test2 <- "a"
new_values<-tryCatch(
{
print("hello")
stop()
}
, error= function(err){
# I want to change the test1 and test 2 variables to "b" only if error occurred.
test1 <- "b"
test2 <- "b"
return(list(test1=test1,test2=test2))
})
if (is.list(new_values))
{
test1<-new_values$test1
test2<-new_values$test2
}
结果:
> print(test1)
[1] "b"
> print(test2)
[1] "b"
【问题讨论】:
-
它在技术上是在出现错误情况时调用的匿名函数中。所有传统的scoping rules 都适用。虽然
<<-受到强烈警告,但它是R 提供的一个工具,可以谨慎使用。在编写包时经常需要它,并且应该在正常的分析/脚本中进行大量注释或避免。
标签: r exception-handling scope