Raising Errors with stop()
Part of the Logic & Flow section of Coddy's R journey. Lesson 52 of 64.
stop("message") raises an error: the function stops at once, nothing after it runs, and R prints the message. Use it when a function receives input it cannot work with:
check_qty <- function(q) {
if (q <= 0) stop("quantity must be positive")
q
}
print(check_qty(3))
print(check_qty(-1))
print("never printed")Output:
[1] 3
Error in check_qty(-1) : quantity must be positive
Calls: print -> check_qty
Execution haltedThe error text names the call that failed, and Execution halted means the whole script stopped: the last print() never ran. An error is written to the error stream, not to normal output, so on Coddy a test fails when any error or warning is printed.
stopifnot() checks several conditions at once and raises an error for the first one that is FALSE. A named condition uses its name as the message:
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))Output:
[1] 6
Error in area(2, -1) : height must be positive
Calls: print -> area -> stopifnot
Execution haltedBuild the message from the values with paste0() or sprintf(), so the reader sees what was wrong:
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))Output:
Error in get_item(c("a", "b"), 5) : index 5 is past the end (2 items)
Calls: print -> get_item
Execution haltedRaise errors at the start of a function, before any work is done. Checks that stop early keep the rest of the function simple, because it can assume valid input:
withdraw <- function(balance, amount) {
if (amount <= 0) stop("amount must be positive")
if (amount > balance) stop("insufficient funds")
balance - amount
}Challenge
EasyComplete make_order(item, qty, stock). Raise an error with stop():
quantity must be at least 1whenqtyis below 1only <stock> leftwhenqtyis larger thanstock, such asonly 3 left
Otherwise return ordered <qty> x <item>.
The supplied code reads the item, the quantity and the stock, calls your function and prints either its result or Error: followed by the error message, so no test ever shows R's own error text.
Try it yourself
make_order <- function(item, qty, stock) {
# Write your code here
""
}
# Supplied input/output code: keep it as it is
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")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk8Sorting and Grouping
Sorting VectorsSorting by a KeyGrouping with split()Group SummariesRecap - Leaderboard11Error Handling
Raising Errors with stop()Catching with tryCatch()Warnings and finallyValidating InputRecap - Safe Calculator3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler