避免 tryCatch 到 return 某些东西以防失败
Avoid tryCatch to return something in case of fail
在 tryCatch 函数中,当 tryCatch 失败时,我不想 return NULL 或任何东西。
当你为一个对象分配一个表达式时,如果对象已经存在,它的值没有改变,return就会出错,例如:
> x <- 1
> x
[1] 1
> x <- x + "a"
Error in x + "a" : non-numeric argument to binary operator
> x
[1] 1
而且我想使用 tryCatch 实现相同的行为。所以在这个例子中,tryCatch 失败后 "x" 仍然是“1”而不是 NULL。
f <- function(x){
tryCatch(
expr = {
x <- 1 + x
return(x)
}, error = function(cond){
message("error")
})
}
> x <- f(1)
> x
[1] 2
> x <- f("a")
error
> x
NULL
使用 stop
来解决问题:
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
但即使我可以修改第二部分,stop
也不会产生有用的错误消息,即第一部分 "Error in value[3L] :"
还有其他方法吗?谢谢。
如果您只想 stop
不包含错误消息的开头部分,您只需将 call.
参数设置为 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
在 tryCatch 函数中,当 tryCatch 失败时,我不想 return NULL 或任何东西。
当你为一个对象分配一个表达式时,如果对象已经存在,它的值没有改变,return就会出错,例如:
> x <- 1
> x
[1] 1
> x <- x + "a"
Error in x + "a" : non-numeric argument to binary operator
> x
[1] 1
而且我想使用 tryCatch 实现相同的行为。所以在这个例子中,tryCatch 失败后 "x" 仍然是“1”而不是 NULL。
f <- function(x){
tryCatch(
expr = {
x <- 1 + x
return(x)
}, error = function(cond){
message("error")
})
}
> x <- f(1)
> x
[1] 2
> x <- f("a")
error
> x
NULL
使用 stop
来解决问题:
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
但即使我可以修改第二部分,stop
也不会产生有用的错误消息,即第一部分 "Error in value[3L] :"
还有其他方法吗?谢谢。
如果您只想 stop
不包含错误消息的开头部分,您只需将 call.
参数设置为 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