Stop (right now)

Defensive R Programming

Dr. Colin Gillespie

Jumping Rivers

I saw the sign

Sometimes things are just broken

  • We need to raise an error

For example:

1 + "stuff"
Error in 1 + "stuff": non-numeric argument to binary operator
Defensive R Programming

Stop right now thank you very much

To raise an error, we use the stop() function

stop("A Euro 1996 error has occurred")
# Error: A Euro 1996 error has occurred
conf_int <- function(mean, std_dev) {
   if(std_dev <= 0) 
       stop("Standard deviation must be positive")

   c(mean - 1.96 * std_dev, mean - 1.96 * std_dev)
}
Defensive R Programming

Catch em while you can

  • You can't suppress (or ignore) errors
    • The definition of an error is that R can't continue
    • Instead, we catch errors

Defensive R Programming

The try() function

The try() function acts a bit like suppress()

res <- try("Scotland" + "World cup", silent = TRUE)

It tries to execute something, if it doesn't work, it moves on

Defensive R Programming

The try() idiom

res <- try("Scotland" + "World cup", silent = TRUE)
res
[1] 'Error in "Scotland" + "World cup": non-numeric argument to binary operator'
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in "Scotland" + "World cup": 
                            non-numeric argument to binary operator>
Defensive R Programming

The try() idiom

result <- try("Scotland" + "World cup", silent = TRUE)
class(result)
[1] "try-error"
if(class(result) == "try-error")
  ## Do something useful
Defensive R Programming

Let's practice

Defensive R Programming

Preparing Video For Download...