[R] How to catch both warnings and errors?

Martin Maechler maechler at stat.math.ethz.ch
Thu Dec 9 12:33:15 CET 2010


>>>>> Marius Hofert <m_hofert at web.de>
>>>>>     on Mon, 6 Dec 2010 11:10:17 +0100 writes:

    > 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 :

> str( tryCatch.W.E( log( 2 ) ) )
List of 2
 $ value  : num 0.693
 $ warning: NULL

> str( tryCatch.W.E( log( -1) ) )
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"

> str( tryCatch.W.E( log("a") ) )
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



More information about the R-help mailing list