warnings and tryCatch() (Was: RE: [R] catching the warnings)

Henrik Bengtsson Henrik.Bengtsson at matstat.lu.se
Fri Jun 4 00:56:13 CEST 2004


Seeing this question I was thinking of using tryCatch() to "catch" warnings.
Here is an example:

doWarn <- function() {
  a <<- 1
  warning("Wow!")
  a <<- 2
}

lastError <- lastWarning <- NULL
tryCatch({ 
  x <- 2 
  doWarn()
  x <- 3
  stop("Oops.")
  x <- 4
}, warning = function(warn) { 
  lastWarning <<- warn
}, error = function(err) { 
  lastError <<- err
})
stopifnot(a==1)
stopifnot(x==2)
stopifnot(inherits(lastWarning, "simpleWarning"))
stopifnot(is.null(lastError))

However, as the example shows, as soon as a warning is caught, tryCatch()
returns without evaluating the rest of the expressions. My question: is
there a simple way to continue the evaluation of expressions following the
expression that generated the condition? For instance, can I continue at "a
<<- 2" inside doWarn() by "doing something" within the warning handler? 

I have noticed withCallingHandlers():

lastError <- lastWarning <- NULL
withCallingHandlers({ 
  x <- 2 
  doWarn()
  x <- 3
  stop("Oops.")
  x <- 4
}, warning = function(warn) { 
  lastWarning <<- warn
}, error = function(err) { 
  lastError <<- err
})
stopifnot(a==2)
stopifnot(x==3)
stopifnot(inherits(lastWarning, "simpleWarning"))
stopifnot(inherits(lastError, "simpleError"))

Is the latter intended for what I am asking for? It will solve it for
warnings, but it will not allow to restart/continue after an error. Also, in
this case the error message is shown.

Cheers

Henrik Bengtsson


-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Roger D. Peng
Sent: Thursday, June 03, 2004 2:43 PM
To: Marc Mamin
Cc: r-help at stat.math.ethz.ch
Subject: Re: [R] catching the warnings


The warnings are stored in a variable `last.warning' in the workspace. 
  warnings() simply prints this variable.

-roger

Marc Mamin wrote:
> Hello,
> 
> I'd like to catch the warnings in a variable in order to evaluate 
> them, but...
> 
> 
> 
>>tt<-warnings()
> 
> Warning messages:
> 1: XML Parsing Error: test.xml:2: xmlParseStartTag: invalid element 
> name
> 2: XML Parsing Error: test.xml:3: Extra content at the end of the document
> 
>>tt
> 
> NULL
> 
> is there a way to achieve this (R1.8.1)?
> 
> thanks,
> 
> Marc
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list 
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
>

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html




More information about the R-help mailing list