立刻停止

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 防禦式程式設計

一起來練習吧!

R 防禦式程式設計

Preparing Video For Download...