rtry-catchwarnings

How can I execute a statement and ignore warnings with tryCatch?


I tried the following code:

x <- NULL
tryCatch(
  x <- sqrt(-1),
  warning = function(cond) print(paste("Ignore: ", conditionMessage(cond)))
)
# [1] "Ignore:  NaNs produced"

Expected output:

# [1] "Ignore:  NaNs produced"
x
#NaN

Notice that x is still NULL. No value has been assigned.


Solution

  • When you tryCatch(.., warning=), the first time the warning happens, the expression is interrupted and control is never returned to it. In order to "ignore" warnings, you need withCallingHandlers and invokeRestart("mufflewarning").

    withCallingHandlers(
      x <- sqrt(-1),
      warning = function(w) invokeRestart("muffleWarning"))
    x
    # [1] NaN
    

    One good reference for studying error/warning conditions is https://adv-r.hadley.nz/conditions.html.

    I think there are two times when it makes sense to me to use "muffleWarning" instead of suppressWarnings: