立刻停止

R 防御式编程

Dr. Colin Gillespie

Jumping Rivers

我看到了信号

有时事情就是坏了

  • 我们需要抛出错误

例如:

1 + "stuff"
Error in 1 + "stuff": non-numeric argument to binary operator
R 防御式编程

现在就停止,谢谢合作

要抛出错误,使用 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)
}
R 防御式编程

尽快捕获

  • 你无法抑制(或忽略)错误
    • 错误的定义是 R 无法继续
    • 我们改为捕获错误

R 防御式编程

try() 函数

try() 有点像 suppress()

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

它尝试执行;若失败,则继续向下运行

R 防御式编程

try() 的惯用法

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>
R 防御式编程

try() 的惯用法

result <- try("Scotland" + "World cup", silent = TRUE)
class(result)
[1] "try-error"
if(class(result) == "try-error")
  ## Do something useful
R 防御式编程

Vamos praticar!

R 防御式编程

Preparing Video For Download...