Programmazione R difensiva
Dr. Colin Gillespie
Jumping Rivers
A volte le cose sono semplicemente rotte
Per esempio:
1 + "stuff"
Error in 1 + "stuff": non-numeric argument to binary operator
Per generare un errore, usiamo la funzione 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)
}

La funzione try() si comporta un po’ come suppress()
res <- try("Scotland" + "World cup", silent = TRUE)
Prova a eseguire qualcosa; se fallisce, passa oltre
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
Programmazione R difensiva