Programação Defensiva em R
Dr. Colin Gillespie
Jumping Rivers
Às vezes as coisas quebram mesmo
Por exemplo:
1 + "stuff"
Error in 1 + "stuff": non-numeric argument to binary operator
Para gerar um erro, usamos a função stop()
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)
}

A função try() age um pouco como suppress()
res <- try("Scotland" + "World cup", silent = TRUE)
Ela tenta executar algo; se não funcionar, segue em frente
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
Programação Defensiva em R