Menu
Coddy logo textTech

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 halted

The 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 halted

Build 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 halted

Raise 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 icon

Challenge

Easy

Complete make_order(item, qty, stock). Raise an error with stop():

  • quantity must be at least 1 when qty is below 1
  • only <stock> left when qty is larger than stock, such as only 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")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler