tryCatch: Extension of base::tryCatch

Description Usage Arguments Details Note on backwards compatibility Note Examples

View source: R/Fixes-extensions.R

Description

The regular base::tryCatch calls a function whenever expr generates an error, which means this function gets its own environment. However, sometimes it's easier to evaluate any code in the same environment as expr (see examples).
Therefore this extension can work with expressions as well, which are then evaluated in the calling context. If this expression returns a function, then that function is called with the condition-object. Note that 'expression' here is used in the sense of 'some R-code', so error=function(e) {e$message} is seen as a very simple expression, which returns a function, which is then called. This means that you can still use the same calls as in base::tryCatch.

Usage

1
tryCatch(expr, ..., finally)

Arguments

expr

Expressions to evaluate that might throw an error

...

Handlers to call if expr throws a condition

finally

expression that is always evaluated before returning or exiting

Details

For use of the condition-object in the main expressions, you can access it under the name "cond" if there is no variable under that name yet. If there is one, this variable is left as-is, and the current condition-object can be accessed with get('cond', parent.frame(2)).
The latter form can always be used (for cases when you're unsure of its existence)

Note on backwards compatibility

This function is meant as a stand-in replacement for base::tryCatch, but there are differences in the calling stack.
See for example the difference in the options you can choose from in the following calls: base::tryCatch(stop(), error=function(e) recover())
vs
tryCatch(stop(), error=function(e) recover()

Therefore there may be some differences in debugging code as well, and code should not rely on any output of parent.frame(n) or length(sys.calls()) etc.

Note

All current variables are potentially modified by the condition-throwing expression, which may be very desirable (for debugging) or very undesirable/confusing (as some objects can be in an unexpected/corrupted state)

Examples

1
2
3
4
5
6
7
errorlog <- character(0) # Or some other previous log
tryCatch({step <- 1;stop('SomeError');step <- 2},
  warning=function(w) print(w),
  error={errorlog <- c(errorlog, paste("\nError occured:\n", cond$message, "\nat step:", step))
         step <- 0
         function(e) {err <- getOption('error'); if(!is.null(err)) eval(err)}
  })

EmilBode/EmilMisc documentation built on Feb. 24, 2020, 4:11 p.m.