Skip to content
Prev 322860 / 398503 Next

ODE solver

Using options(warn=2) is the easiest way to get this function to stop when
it makes the warning, but it will stop at any warning, not just the one you
are worried about.  You can use withCallingHandlers() or tryCatch() to be
more selective.  E.g., the following will stop on any warning that has "time"
in the warning message but willl print the warning message and continue
for other warnings.

catchTimeWarning <- function(expr) {
   withCallingHandlers(expr, 
            warning=function(e){
               warningMsg <- conditionMessage(e)
               if (grepl("time", warningMsg)) {
                  stop(warningMsg)
               } else {
                  message(warningMsg)
                  invokeRestart("muffleWarning")
               }
            }
   )
}

Here is an example of using it
{
    # naive way to compute factorial
    if (n < 1 || n != round(n)) {
        warning("This will take a very long time")
    }
    fac <- n
    while ((n <- n - 1) != 0) {
        fac <- fac * n
    }
    if (is.infinite(fac)) {
        warning("Factorial calculation overflowed")
    }
    fac
}
[1] 120
Factorial calculation overflowed
[1] Inf
Error in function (e)  : This will take a very long time

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com