I am dealing with a function that is throwing both errors and warnings. (related: A Warning About Warning )
Often, a warning will proceed an error. In these situations, I would like to disregard the warning and process only the error.
On the other hand, if there is only a warning (with no error), then I would like to catch the warning.
I am attempting to work with the notoriously-easy-to-use tryCatch
.
My immediate question is:
Is there a way to force tryCatch
to process error
s before warning
s (or to disregard warnings when there is an error)?
My understanding from the ?tryCatch
documentation is that conditions are handled FIFO, in which case the answer to my immediate question is No - at least not directly. In which case, is it possible to process the warning and then have the function continue while still catching errors?
solutions NOT available to me:
suppressWarnings
# I would like to still catch and handle the warningsoptions(warn=2)
# certain warnings are harmless
relevant from `?tryCatch`
If a condition is signaled while evaluating expr then established handlers are checked, starting with the most recently established ones, for one matching the class of the condition. When several handlers are supplied in a single tryCatch then the first one is considered more recent than the second. If a handler is found then control is transferred to the tryCatch call that established the handler, the handler found and all more recent handlers are disestablished, the handler is called with the condition as its argument, and the result returned by the handler is returned as the value of the tryCatch call.
Below is a toy example:
F.errorAndWarning <- function() {
warning("Warning before the error")
cat("I have moved on.")
stop("error")
TRUE
}
F.error <- function() {stop("error"); TRUE}
test <- function(F)
tryCatch(expr= {F}()
, error=function(e) cat("ERROR CAUGHT")
, warning=function(w) cat("WARNING CAUGHT")
)
test(F.error)
# ERROR CAUGHT
test(F.errorAndWarning)
# WARNING CAUGHT
Expected / ideal output:
test(F.errorAndWarning)
# ERROR CAUGHT
See Question&Answers more detail:os