Julien Navarre
Julien Navarre

Reputation: 7830

Avoid tryCatch to return something in case of fail

in a tryCatch function, I would like to don't return NULL or anything when the tryCatch fail.

When you assign to an object an expression which returns an error if the object already exists his value isnt changed, e.g :

> x <- 1
> x
[1] 1
> x <- x + "a"
Error in x + "a" : non-numeric argument to binary operator
> x
[1] 1

And I would like to have the same behaviour using a tryCatch. So in this example after the tryCatch failed "x" is still "1" and not 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

Use stop do the trick :

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

But even if I can modify the 2nd part, stop produces not rly helpful error messages, i.e the 1st part "Error in value[3L] :"

Is there another way to do it ? Thanks.

Upvotes: 1

Views: 979

Answers (1)

cdeterman
cdeterman

Reputation: 19960

If you just want stop to not include the beginning part of the error message you just set the call. argument to 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

Upvotes: 3

Related Questions