Defensive R Programming
Dr. Colin Gillespie
Jumping Rivers
Sometimes things are just broken
For example:
1 + "stuff"
Error in 1 + "stuff": non-numeric argument to binary operator
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)
}
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
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>
result <- try("Scotland" + "World cup", silent = TRUE)
class(result)
[1] "try-error"
if(class(result) == "try-error")
## Do something useful
Defensive R Programming