R 避免尝试在失败时返回某些内容

R 避免尝试在失败时返回某些内容,r,error-handling,try-catch,R,Error Handling,Try Catch,在tryCatch函数中,我不希望在tryCatch失败时返回NULL或任何内容 当您为对象指定一个表达式时,如果该对象已存在,则该表达式将返回一个错误,其值不会更改,例如: > x <- 1 > x [1] 1 > x <- x + "a" Error in x + "a" : non-numeric argument to binary operator > x [1] 1 但是,即使我可以修改第二部分,stop也会产生不太有用的错误消息,即第一部分“值

在tryCatch函数中,我不希望在tryCatch失败时返回NULL或任何内容

当您为对象指定一个表达式时,如果该对象已存在,则该表达式将返回一个错误,其值不会更改,例如:

> x <- 1
> x
[1] 1
> x <- x + "a"
Error in x + "a" : non-numeric argument to binary operator
> x
[1] 1
但是,即使我可以修改第二部分,
stop
也会产生不太有用的错误消息,即第一部分“值中的错误[3L]:”


还有别的办法吗?谢谢。

如果您只想
stop
不包含错误消息的开头部分,只需将
调用设置为
FALSE

f <- function(x){
    tryCatch(
        expr = {
            x <- 1 + x
            return(x)
        }, error = function(cond){
            stop("non-numeric argument to binary operator", call.=FALSE)
        })
}
x <- 1
x <- f("a")

Error: non-numeric argument to binary operator 

x
[1] 1

f
stop
将返回您在其中输入的任何字符串。如果您喜欢初始错误,您不能将
stop(“错误”)
替换为
stop(“二进制运算符的非数字参数”)
吗?我知道,,,但是使用
stop
您仍然有无法编辑的第一部分:
>stop(“错误”)错误:error
谢谢!在我的例子中,它使错误消息更容易理解,而不需要开头部分!
f <- function(x){
  tryCatch(
    expr = {
      x <- 1 + x
      return(x)
    }, error = function(cond){
      stop("error")
    })
}

> x <- f(1)
> x
[1] 2
> x <- f("a")
Error in value[[3L]](cond) : error
> x
[1] 2
f <- function(x){
    tryCatch(
        expr = {
            x <- 1 + x
            return(x)
        }, error = function(cond){
            stop("non-numeric argument to binary operator", call.=FALSE)
        })
}
x <- 1
x <- f("a")

Error: non-numeric argument to binary operator 

x
[1] 1