Skip to content
Prev 244416 / 398506 Next

How to catch both warnings and errors?

> Hmm... still not quite what I was hoping for... 
indeed.

We (Marius and I) now sat together,
and have constructed the following quite nice,
quite general solution:

With thanks to Luke Tierney's explanation (from 2004 !)
     http://tolstoy.newcastle.edu.au/R/help/04/06/0217.html
and Bill Dunlap's note (mentioned in Marius' original post):

##' We want to catch *and* save both errors and warnings, and in the case of
##' a warning, also keep the computed result.
##'
##' @title tryCatch both warnings and errors
##' @param expr
##' @return a list with 'value' and 'warning', where 
##'  'value' may be an error caught.
##' @author Martin Maechler
tryCatch.W.E <- function(expr)
{
    W <- NULL
    w.handler <- function(w){ # warning handler
	W <<- w
	invokeRestart("muffleWarning")
    }
    list(value = withCallingHandlers(tryCatch(expr, error = function(e) e),
				     warning = w.handler),
	 warning = W)
}


Testing it here for Marius' three cases :
List of 2
 $ value  : num 0.693
 $ warning: NULL
List of 2
 $ value  : num NaN
 $ warning:List of 2
  ..$ message: chr "NaNs wurden erzeugt"
  ..$ call   : language log(-1)
  ..- attr(*, "class")= chr [1:3] "simpleWarning" "warning" "condition"
List of 2
 $ value  :List of 2
  ..$ message: chr "Nicht-numerisches Argument f?r mathematische Funktion"
  ..$ call   : language log("a")
  ..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
 $ warning: NULL

---
Martin Maechler, ETH Zurich