Learn R Programming

infix (version 0.1.0)

except: Simple Error Handling

Description

Use this method to handle errors. The function evaluates an expression, and if it raises an error then evaluates a second expression.

Usage

tryExcept(expr, except = { }, error = function(e) { })

expr %except% except

Arguments

expr

Expression to be evaluated.

except

Expression to be evaluated if expr raises an error. By default it is an empty expression.

error

Handler function for an error condition occurred during the evaluation of expr. It's output is not used, as the output in case of an error is the evaluation of except. By default it is an empty function.

Details

tryExcept is a wrapper around tryCatch, but it allows you to evaluate an expression except when an error occurs to the first expression argument expr. Note that, if expr raises an error, the code evaluated before the error will be in use.

Examples

Run this code
# NOT RUN {
# No errors are raised
tryExcept(stop())

# If 'expr' has no errors
tryExcept({
  foo <- "foo"
}, except = {
  foo <- "foo bar"
})
print(foo) # "foo"

# If 'expr' has an error
tryExcept({
  foo <- "foo"
  stop()
}, except = {
  foo <- "foo bar"
})
print(foo) # "foo bar"

# Running it with the infix operator
{foo <- "foo"} %except% {foo <- "foo bar"}
print(foo) # "foo"

{ foo <- "foo"
  stop()
} %except% {
  foo <- "foo bar"
}
print(foo) # "foo bar"
# }

Run the code above in your browser using DataLab