stop()でエラーを発生させる
CoddyのRジャーニー「ロジックとフロー」セクションの一部。レッスン 52/64。
stop("message") はエラーを発生させます。この関数は直ちに停止し、それ以降の処理は実行されず、R はメッセージを出力します。関数が処理できない入力を受け取ったときに使用します。
check_qty <- function(q) {
if (q <= 0) stop("quantity must be positive")
q
}
print(check_qty(3))
print(check_qty(-1))
print("never printed")出力:
[1] 3
Error in check_qty(-1) : quantity must be positive
Calls: print -> check_qty
Execution haltedエラーテキストには失敗した呼び出しが示され、Execution haltedはスクリプト全体が停止したことを意味します。最後のprint()は実行されませんでした。エラーは通常の出力ではなくエラーストリームに書き込まれるため、Coddyではエラーまたは警告が1つでも出力されるとテストは失敗します。
stopifnot()は複数の条件を一度にチェックし、FALSEである最初の条件に対してエラーを発生させます。名前付き条件では、その名前がメッセージとして使用されます。
area <- function(w, h) {
stopifnot("width must be positive" = w > 0, "height must be positive" = h > 0)
w * h
}
print(area(2, 3))
print(area(2, -1))出力:
[1] 6
Error in area(2, -1) : height must be positive
Calls: print -> area -> stopifnot
Execution haltedpaste0()またはsprintf()を使って値からメッセージを組み立て、何が問題だったのかが読者にわかるようにします:
get_item <- function(items, i) {
if (i > length(items)) stop(sprintf("index %d is past the end (%d items)", i, length(items)))
items[i]
}
print(get_item(c("a", "b"), 5))出力:
Error in get_item(c("a", "b"), 5) : index 5 is past the end (2 items)
Calls: print -> get_item
Execution halted関数の先頭で、処理を行う前にエラーを発生させます。早期に処理を中止するチェックによって、入力が有効であると仮定できるため、関数の残りの部分をシンプルに保てます。
withdraw <- function(balance, amount) {
if (amount <= 0) stop("amount must be positive")
if (amount > balance) stop("insufficient funds")
balance - amount
}チャレンジ
簡単make_order(item, qty, stock)を完成させてください。stop()でエラーを発生させます。
qtyが1未満の場合はquantity must be at least 1qtyがstockより大きい場合はonly <stock> left(例:only 3 left)
それ以外の場合はordered <qty> x <item>を返します。
提供されたコードは item、quantity、stock を読み取り、あなたの関数を呼び出して、その結果またはError: に続くエラーメッセージのいずれかを出力します。そのため、テストでR独自のエラーテキストが表示されることはありません。
自分で試してみよう
make_order <- function(item, qty, stock) {
# ここにコードを書いてください
""
}
# 提供された入出力コード: そのままにしておいてください
input <- suppressWarnings(readLines(file("stdin")))
result <- tryCatch(make_order(input[1], as.numeric(input[2]), as.numeric(input[3])),
error = function(e) paste("Error:", conditionMessage(e)))
cat(result, sep = "\n")
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
自分で練習してみよう: Rオンラインコンパイラ