Menu
Coddy logo textTech

העלאת שגיאות באמצעות stop()

חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-R של Coddy. שיעור 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 בדיקה נכשלת כשמודפסת שגיאה או אזהרה כלשהי.

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 halted

בנה את ההודעה מהערכים באמצעות paste0() או 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
}
challenge icon

אתגר

קל

השלם את make_order(item, qty, stock). העלה שגיאה באמצעות stop():

  • quantity must be at least 1 כאשר qty קטן מ־1
  • only <stock> left כאשר qty גדול מ־stock, למשל only 3 left

אחרת, החזר ordered <qty> x <item>.

הקוד שסופק קורא את הפריט, את הכמות ואת המלאי, קורא לפונקציה שלך ומדפיס את התוצאה שלה או את 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")
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה לוגיקה וזרימת תוכנית

תרגלו בעצמכם: קומפיילר R אונליין