Home > Enterprise >  tryCatch() does not suppress the error messages
tryCatch() does not suppress the error messages

Time:11-03

I would like to create a function that does not print any error messages.

Let's say I have the following data:

library(fitdistrplus)
vec <- rnorm(100)

Then the following gives an error message:

fitdist(vec, "exp")
#> Error in computing default starting values.
#> Error in manageparam(start.arg = start, fix.arg = fix.arg, obs = data, : Error in start.arg.default(obs, distname) : 
#>   values must be positive to fit an exponential  distribution

Now I would like to create a function that does return NULL. I tried this with tryCatch(). The problem is that fit_fn() still returns the error 'Error in computing default starting values':

fit_fn <- function(x){
  tryCatch(fitdist(x, "exp"), error = function(e){ NULL })
}

fit_fn(vec)
#> Error in computing default starting values.
#> NULL

What is the way to do this? Only NULL should be printed here:

fit_fn(vec)
#> NULL

Created on 2021-11-02 by the reprex package (v2.0.1)

CodePudding user response:

Desipte the fact that it says it's an error, the message that's being displayed is done not via the error mechanism, but the output is being printed directly to the console because it's already in it's own error handler. If you want to suppress that message, you'll need to capture the output of the function. Then you can ignore that output. You can do that with

fit_fn <- function(x){
  capture.output(result <- tryCatch(fitdist(x, "exp"), 
           error = function(e){ NULL }))
  result
}
fit_fn(vec)
# NULL
  • Related