tryCatch错误范围{}

tryCatch错误范围{},r,R,这将输出“未发现错误!”两次 x使用environment(f0)[[“x”]] [1] “哎呀” >x 错误:找不到对象“x” xdoesn这不是将x放入全局范围吗?我只想进入tryCatch的范围,而不是全球范围。我将对其进行编辑,以澄清这正是我想要的want@hedgedandlevered但是你想在tryCatch之外打印(x),所以tryCatch“外部”的打印(x)实际上与我的答案中添加的tryCatch@hedgedandlevered的正文(非错误部分)的范围相同,以进一步澄清@

这将输出“未发现错误!”两次

x使用
environment(f0)[[“x”]]
[1] “哎呀”
>x
错误:找不到对象“x”

xdoesn这不是将x放入全局范围吗?我只想进入tryCatch的范围,而不是全球范围。我将对其进行编辑,以澄清这正是我想要的want@hedgedandlevered但是你想在tryCatch之外打印(x),所以
tryCatch“外部”的打印(x)实际上与我的答案中添加的tryCatch@hedgedandlevered的正文(非错误部分)的范围相同,以进一步澄清
@hedgedandlevered:

x<-"no error found!"
dontchangex <- function()
{
  tryCatch(
    {
      x<- "break this"+1  
    },error= function(e)
    {
      x<-"oh no :("
    })
  print(x)
}
dontchangex()
print(x)
x<-"no error found!"
tryCatch(
  {
    x<- "break this"+1  
  },error= function(e)
  {
    x <<- conditionMessage(e)
  })
print(x)
f = function() {
    if (runif(1) > .8) stop("oops")
    TRUE
}

g = function() {
    ## on error, warn user but continue with sentinel 'FALSE'
    tryCatch(f(), error=function(err) {
        warning(conditionMessage(err))
        NA
    })
}
> options(warn=1)
> replicate(10, g())
Warning in value[[3L]](cond) : oops
Warning in value[[3L]](cond) : oops
 [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE NA NA  TRUE  TRUE
x <- 1
fun = function() {
    x <- "OK"
    tryCatch(stop("oops"), error=function(e) x <<- conditionMessage(e))
    x
}
> fun()
[1] "oops"
> x
[1] 1
f = function() {
    x <- 0
    function() {
        tryCatch({
            stop("oops")
        }, error=function(e) {
            x <<- conditionMessage(e)
        })
        ls()
    }
}
> f0 <- f()
> environment(f0)[["x"]]
[1] 0
> f0 <- f()
> environment(f0)[["x"]]
[1] 0
> f0()
character(0)
> environment(f0)[["x"]]
[1] "oops"
> x
Error: object 'x' not found
x<-"no error found!"
dontchangex <- function()
{
  errorFound <- TRUE
  tryCatch(
    {
      x<- "break this"+1  
      errorFound <- FALSE
    },error= function(e){}
  )
  if(errorFound) x<-"oh no :("
  print(x)
}
dontchangex()
print(x)