חלקPart 2: פונקציות וקוד אמיתיFunctions & real code
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
שגיאות ו-try/exceptErrors & try/except
איך קוראים Traceback, סוגי חריגות, try/except/else/finally ו-raise.
How to read a traceback, exception types, try/except/else/finally and raise.
הנקודות החשובותKey points
- מלמטה למעלהBottom to top
- השורה האחרונה: סוג והסברLast line: type and message
try:קוד שעלול להיכשלtry:code that might failexcept ValueError:מה עושים אם נכשלexcept ValueError:what to do if it failswhile True+try+breakwhile True+try+break- ההודעה אומרת מה לתקןThe message says what to fix
else: רץ אם לא הייתה שגיאהelse: runs if there was no errorfinally: רץ תמידfinally: always runsraise ValueError("הסבר")raise ValueError("message")
מונחיםTerms
- חריגה (exception)exception: אירוע שגיאה בזמן ריצה. אם אף אחד לא תופס אותה, התוכנית נעצרת ומדפיסה Traceback.An error event at run time. If nobody catches it, the program stops and prints a traceback.
- try / excepttry / except: בלוק שמנסה להריץ קוד (
try) ותופס חריגה מסוג מסוים (except) במקום לקרוס.A block that tries some code (try) and catches an exception of a given type (except) instead of crashing. - raiseraise: זריקת חריגה בעצמכם, למשל כשקלט לא חוקי:
raise ValueError("...").Throwing an exception yourself, e.g. on invalid input:raise ValueError("..."). - מחסנית קריאותcall stack: שרשרת הפונקציות שקראו זו לזו עד הנקודה הנוכחית. ה-Traceback מציג אותה.The chain of functions that called each other up to the current point. A traceback shows it.
Cheatsheet
קריאת TracebackReading tracebacks
def average(nums):
return sum(nums) / len(nums)
def report(shelf):
pages = [b["pages"] for b in shelf]
print("avg:", average(pages))
try/excepttry/except
raw = input("כמה עמודים? ")
try:
pages = int(raw)
print(f"בערך {pages // 40} שעות קריאה")
except ValueError:
print(f"\"{raw}\" זה לא מספר. נסו שוב עם ספרות.")raw = input("How many pages? ")
try:
pages = int(raw)
print(f"About {pages // 40} hours of reading")
except ValueError:
print(f"\"{raw}\" isn't a number. Try again with digits.")לולאת קלטInput loop
while True:
raw = input("דירוג 1-5: ")
try:
rating = int(raw)
except ValueError:
print("צריך מספר שלם")
continuewhile True:
raw = input("Rating 1-5: ")
try:
rating = int(raw)
except ValueError:
print("Please type a whole number")
continueelse/finallyelse/finally
def per_day(pages, days):
try:
result = pages / int(days)
except ValueError:
return "ימים חייבים להיות מספר"
except ZeroDivisionError:
return "אי אפשר 0 ימים"def per_day(pages, days):
try:
result = pages / int(days)
except ValueError:
return "days must be a number"
except ZeroDivisionError:
return "can't be 0 days"raiseraise
def set_rating(book, stars):
if not 1 <= stars <= 5:
raise ValueError(f"rating must be 1-5, got {stars}")
book["rating"] = stars
book = {"title": "Dune"}
set_rating(book, 5)סוגי חריגותException types
tests = [lambda: int("abc"), lambda: "a" + 1, lambda: {}["x"], lambda: [1][5], lambda: 1 / 0]
for t in tests:
try:
t()
except Exception as e:
print(f"{type(e).__name__:<18} {e}")שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
ValueError | תופסים סוג אחר ממה שקורה בפועל. ה-except לא תופס, והתוכנית עדיין נופלת.Catching a different type from what actually happens. The except doesn't catch it, and the program still crashes. | ValueError לא נתפס כי ה-except מחכה ל-ZeroDivisionError. כותבים את הסוג שמופיע בשורה האחרונה של ה-Traceback.ValueError isn't caught because the except waits for ZeroDivisionError. Write the type from the traceback's last line. |
RuntimeError | עוטפים קוד גדול מדי ב-try, ותופסים בטעות שגיאה אחרת לגמרי.Wrapping too much code in try and catching a completely different error by mistake. | except Exception תפס את ה-NameError של pagez והסתיר באג. עוטפים רק את השורה שעלולה להיכשל, ותופסים סוג מסוים.except Exception caught the pagez NameError and hid a bug. Wrap only the line that can fail, and catch a specific type. |
SyntaxError | except בלי try לפניו.except without a try before it. | SyntaxError: invalid syntax: except חייב לבוא מיד אחרי בלוק try.SyntaxError: invalid syntax: except must come right after a try block. |
ValueError | זורקים שגיאה בלי לתפוס אותה: התוכנית נעצרת, אבל עם הודעה ברורה. זה בדיוק המטרה כשמדובר בבאג.Raising without catching: the program stops, but with a clear message. That's exactly the point for a bug. | ValueError: rating must be 1-5, got 9: ההודעה אומרת בדיוק מה לא בסדר ואיזה ערך הגיע. עוטפים ב-try רק אם יש מה לעשות עם זה.ValueError: rating must be 1-5, got 9: the message says exactly what's wrong and which value arrived. Wrap in try only if there's something useful to do. |
SyntaxError | מנסים לתפוס שגיאת תחביר. SyntaxError קורית לפני שהקוד בכלל רץ, ולכן try לא עוזר.Trying to catch a syntax error. SyntaxError happens before the code even runs, so try doesn't help. | SyntaxError: '(' was never closed: Python בודקת תחביר לפני הריצה, אז ה-try לא קיים עדיין. מתקנים את הקוד עצמו.SyntaxError: '(' was never closed: Python checks syntax before running, so the try doesn't exist yet. Fix the code itself. |