一如Nothingness概念中所探討的,R 有各種方式來表示不存在的資料(NULL)、未知的資料(NA),或是數學上無效的資料(NaN、Inf)。
一般來說,R 會試著用這些值就地標示問題,並繼續執行,而不會拋出例外。
stop()有些問題太過根本,無法讓程式繼續執行。
這種情況下,請使用stop(msg)立刻中止程式、產生Error,並印出msg。
f <- function() {
stop("I have a problem")
}
f()
#> Error in f() : I have a problem
stopifnot()類似其他語言中的assert,這是stop()的便利包裝函式。
它的參數是任意數量、以逗號分隔的布林條件,只有當這些條件全為TRUE時,程式才會繼續執行。
stopifnot(1 < 2) # continues OK
stopifnot(1 < 2, 1 == 2)
#> Error: 1 == 2 is not TRUE
warning()和message()
這些是對非致命狀況的回應,例如:
w <- function() {
warning("something strange happened")
-1
}
w()
#> [1] -1
#> Warning message:
#> In w() : something strange happened
# if warnings are not wanted
suppressWarnings(w())
#> [1] -1
suppressWarnings()函式有時在 Exercism 上很好用,可以避免讓非預期的輸出混淆測試執行器。
Elena 是報紙工廠的新任品質經理。 她才剛到公司,便決定檢視工廠裡的一些流程,看看有什麼可以改進的地方。
她發現技術人員做了許多手動的品質檢查。
她看到這是導入自動化的好機會,於是請你這位自由接案的開發者設計一套軟體,來監控部分機器。
你的第一項任務,是寫一套軟體來監控生產室的濕度。 公司的軟體已經連接了一個感測器,會定期回傳房間的濕度百分比。
你需要在軟體中實作一個函式,當濕度百分比過高時會拋出錯誤。
這個函式應該命名為check_humidity_level,並以濕度百分比作為參數。
如果百分比超過 70%,你應該以錯誤中止執行(訊息內容不重要)。
否則,發出一則包含「humidity test passed」的訊息,並回傳TRUE來確認測量結果正常。
check_humidity_level(60)
#> humidity test passed
#> [1] TRUE
check_humidity_level(100)
#> Error in check_humidity_level(100) : pct_humidity <= 70 is not TRUE
Elena 對你的第一項任務非常滿意,請你負責監控機器的溫度。 你和技術人員 Greg 聊天時得知,如果機器的溫度超過 500°C,技術人員就會開始擔心過熱。
機器上裝有一個感測器,用來測量內部溫度。 你要知道,這個感測器非常敏感,而且經常損壞。 這種情況下,技術人員就必須更換它。
你的工作是實作一個函式report_overheating,以溫度作為參數,並在感測器損壞或機器開始過熱時拋出錯誤。
由於之後必須根據不同的錯誤做出不同反應,你需要一套機制來區分這兩種錯誤。
NULL。
這種情況下,你應該以錯誤訊息中止執行,訊息字串中要包含「Sensor Broken」。FALSE。"temperature check passed: t °C",其中t是溫度,並回傳TRUE。report_overheating(NULL)
#> Error in report_overheating(NULL) : Sensor Broken
report_overheating(800)
#> Error in report_overheating(800) : Overheating: 800 C
report_overheating(550)
#> [1] FALSE
#> Warning message:
#> In report_overheating(550) : Risk of overheating: 550 C
report_overheating(450)
#> temperature check passed: 450 °C
#> [1] TRUE
現在你的機器已經能偵測錯誤,你也有自訂的機器錯誤,接著你要加入一個包裝函式,用來回報整體運作情況。 除了回傳前面幾個函式的日誌,這個包裝函式還需要依據發生的失敗類型加入日誌。
check_humidity_level()和report_overheating()輸出各自的日誌。實作一個函式monitor_the_machine(),以濕度與溫度作為引數。
# Working well
monitor_the_machine(53, 200)
#> humidity test passed
#> temperature check passed: 200 °C
#> All OK!
# High humidity
monitor_the_machine(90, 200)
#> Error in check_humidity_level(pct_humidity) :
#> pct_humidity <= 70 is not TRUE
# Faulty sensor
monitor_the_machine(53, NULL)
#> humidity test passed
#> Error in report_overheating(temperature) : Sensor Broken
# Mild overheating
monitor_the_machine(53, 550)
#> humidity test passed
#> Warning message:
#> In report_overheating(temperature) : Risk of overheating: 550 C
# Dangerous overheating: shutdown
monitor_the_machine(53, 650)
#> humidity test passed
#> Error in report_overheating(temperature) : Overheating: 650 C