שגיאות ו-try/exceptErrors & try/except
איך קוראים Traceback, סוגי חריגות, try/except/else/finally ו-raise.
How to read a traceback, exception types, try/except/else/finally and raise.
01לקרוא Traceback ארוךReading a long traceback
כשהשגיאה קורית בתוך פונקציה שנקראה מפונקציה אחרת, ה-Traceback מציג את כל השרשרת: מחסנית הקריאות. קוראים מלמטה: השורה האחרונה אומרת מה, הבלוק שמעליה אומר איפה בדיוק, והבלוקים העליונים מראים איך הגענו לשם.
When an error happens inside a function called by another function, the traceback shows the whole chain: the call stack. Read from the bottom: the last line says what, the block above it says exactly where, and the upper blocks show how we got there.
def average(nums):
return sum(nums) / len(nums)
def report(shelf):
pages = [b["pages"] for b in shelf]
print("avg:", average(pages))
report([])Traceback (most recent call last):
File "/Users/you/python-course/report.py", line 8, in <module>
report([])
~~~~~~^^^^
File "/Users/you/python-course/report.py", line 6, in report
print("avg:", average(pages))
~~~~~~~^^^^^^^
File "/Users/you/python-course/report.py", line 2, in average
return sum(nums) / len(nums)
~~~~~~~~~~^~~~~~~~~~~
ZeroDivisionError: division by zero| שורה ב-TracebackTraceback line | מה היא אומרתWhat it says |
|---|---|
line 8, in <module>line 8, in <module> | הקוד הראשי קרא ל-reportThe main code called report |
line 6, in reportline 6, in report | report קראה ל-averagereport called average |
line 2, in averageline 2, in average | כאן זה נפל בפועלThis is where it actually failed |
ZeroDivisionErrorZeroDivisionError | מה קרה: len של רשימה ריקה הוא 0What happened: an empty list has len 0 |
Traceback הוא כמו שרשרת תחקיר: "מי ביקש ממך?" "היא ביקשה ממני" "ומי ביקש ממנה?". בסוף השרשרת מוצאים מי באמת שבר את הכוס.
A traceback is like a chain of questioning: "who asked you?" "she asked me" "and who asked her?". At the end of the chain you find who really broke the glass.
מפענח שגיאותError decoder
הדביקו כאן Traceback (כל ההודעה, כולל השורה האחרונה) ולחצו פענוח.
Paste a traceback here (the whole message, including the last line) and press Decode.
המפענח עובד גם על כל שגיאה שמופיעה כשלוחצים הרצה בדוגמאות ובתרגילים: ההסבר מופיע מתחת לפלט.
The decoder also works on any error you get when pressing Run in examples and exercises: the explanation appears under the output.
02try / except: לתפוס במקום לקרוסtry / except: catch instead of crash
try מנסה להריץ קוד. אם קורית חריגה מהסוג שכתוב ב-except, Python קופצת לשם במקום לקרוס. תופסים רק את הסוג שמצפים לו, כדי לא להסתיר באגים אחרים.
try attempts some code. If an exception of the type named in except happens, Python jumps there instead of crashing. Catch only the type you expect, so other bugs aren't hidden.
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.")כמה עמודים? lots "lots" זה לא מספר. נסו שוב עם ספרות.
How many pages? lots "lots" isn't a number. Try again with digits.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
try/except הוא כמו רשת ביטחון באקרובטיקה: האקרובט עדיין מנסה את הקפיצה, אבל אם הוא נופל, יש מי שתופס אותו והמופע ממשיך.
try/except is like a safety net for acrobats: the acrobat still tries the jump, but if they fall, something catches them and the show goes on.
תופסים סוג אחר ממה שקורה בפועל. ה-except לא תופס, והתוכנית עדיין נופלת.
Catching a different type from what actually happens. The except doesn't catch it, and the program still crashes.
try:
pages = int("lots")
except ZeroDivisionError:
print("caught")Traceback (most recent call last):
File "/Users/you/python-course/try_demo.py", line 2, in <module>
pages = int("lots")
ValueError: invalid literal for int() with base 10: 'lots'ValueError לא נתפס כי ה-except מחכה ל-ZeroDivisionError. כותבים את הסוג שמופיע בשורה האחרונה של ה-Traceback.ValueError isn't caught because the except waits for ZeroDivisionError. Write the type from the traceback's last line.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
try תופס שגיאה והתוכנית ממשיכה.
try catches an error and the program keeps going.
for d in [2, 0, 5]:
try:
print(10 / d)
except ZeroDivisionError:
print("can't divide by zero")5.0 can't divide by zero 2.0
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03לנסות שוב עד שמצליחיםRetry until it works
הדפוס הכי שימושי: לולאה שמבקשת קלט עד שמגיע קלט תקין. ה-break בתוך ה-try מתבצע רק אם ההמרה הצליחה.
The most useful pattern: a loop that asks for input until it's valid. The break inside try only runs if the conversion succeeded.
while True:
raw = input("דירוג 1-5: ")
try:
rating = int(raw)
except ValueError:
print("צריך מספר שלם")
continue
if 1 <= rating <= 5:
break
print("בין 1 ל-5 בבקשה")
print("⭐" * rating)while True:
raw = input("Rating 1-5: ")
try:
rating = int(raw)
except ValueError:
print("Please type a whole number")
continue
if 1 <= rating <= 5:
break
print("Between 1 and 5, please")
print("⭐" * rating)דירוג 1-5: five צריך מספר שלם דירוג 1-5: 9 בין 1 ל-5 בבקשה דירוג 1-5: 4 ⭐⭐⭐⭐
Rating 1-5: five Please type a whole number Rating 1-5: 9 Between 1 and 5, please Rating 1-5: 4 ⭐⭐⭐⭐
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
זה כמו קופאית שמבקשת שוב את הקוד של כרטיס האשראי, ומסבירה מה היה לא בסדר, במקום לסגור את החנות.
It's like a cashier asking for the card PIN again and explaining what was wrong, instead of closing the shop.
עוטפים קוד גדול מדי ב-try, ותופסים בטעות שגיאה אחרת לגמרי.
Wrapping too much code in try and catching a completely different error by mistake.
try:
pages = int("400")
print(pagez)
except Exception:
raise RuntimeError("got hidden by a broad except: the real problem was a typo")Traceback (most recent call last):
File "/Users/you/python-course/retry.py", line 3, in <module>
print(pagez)
^^^^^
NameError: name 'pagez' is not defined. Did you mean: 'pages'?
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/you/python-course/retry.py", line 5, in <module>
raise RuntimeError("got hidden by a broad except: the real problem was a typo")
RuntimeError: got hidden by a broad except: the real problem was a typoexcept 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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04else ו-finallyelse and finally
אפשר כמה בלוקי except לסוגי שגיאות שונים. else רץ רק אם ה-try הצליח, ו-finally רץ תמיד, גם אחרי שגיאה, ולכן משתמשים בו לניקוי (סגירת קובץ, הודעת סיום).
You can have several except blocks for different error types. else runs only if the try succeeded, and finally always runs, even after an error, so it's used for clean-up (closing a file, a final message).
def per_day(pages, days):
try:
result = pages / int(days)
except ValueError:
return "ימים חייבים להיות מספר"
except ZeroDivisionError:
return "אי אפשר 0 ימים"
else:
return round(result)
finally:
print("(בדיקה הסתיימה)")
print(per_day(412, "7"))
print(per_day(412, "0"))
print(per_day(412, "x"))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"
else:
return round(result)
finally:
print("(check done)")
print(per_day(412, "7"))
print(per_day(412, "0"))
print(per_day(412, "x"))(בדיקה הסתיימה) 59 (בדיקה הסתיימה) אי אפשר 0 ימים (בדיקה הסתיימה) ימים חייבים להיות מספר
(check done) 59 (check done) can't be 0 days (check done) days must be a number
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
finally הוא כמו לכבות את האור כשיוצאים מהחדר: עושים את זה תמיד, לא משנה אם הפגישה הצליחה או התפוצצה.
finally is like switching the light off when leaving a room: you always do it, whether the meeting went well or blew up.
except בלי try לפניו.
except without a try before it.
pages = int("x")
except ValueError:
pages = 0 File "/Users/you/python-course/else_finally.py", line 2
except ValueError:
^^^^^^
SyntaxError: invalid syntaxSyntaxError: invalid syntax: except חייב לבוא מיד אחרי בלוק try.SyntaxError: invalid syntax: except must come right after a try block.05raise: לזרוק שגיאה בעצמכםraise: throw an error yourself
לפעמים הקוד שלכם מגלה בעיה ש-Python לא רואה, כמו דירוג 7 מתוך 5. raise זורק חריגה עם הסבר ברור. כך הבעיה מתגלה מיד, ומי שקרא לפונקציה יכול לתפוס אותה.
Sometimes your code spots a problem Python can't see, like a rating of 7 out of 5. raise throws an exception with a clear message. The problem shows up immediately, and the caller can catch it.
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)
print(book)
try:
set_rating(book, 7)
except ValueError as e:
print("נדחה:", e)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)
print(book)
try:
set_rating(book, 7)
except ValueError as e:
print("Rejected:", e){'title': 'Dune', 'rating': 5}
נדחה: rating must be 1-5, got 7{'title': 'Dune', 'rating': 5}
Rejected: rating must be 1-5, got 7צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
raise הוא כמו מנהל מחסן שמחזיר משלוח פגום עם פתק "חסרים 3 ארגזים": עדיף לעצור עכשיו עם הסבר מאשר לגלות את הבעיה בעוד חודש.
raise is like a warehouse manager sending back a damaged delivery with a note "3 boxes missing": better to stop now with a reason than discover it in a month.
זורקים שגיאה בלי לתפוס אותה: התוכנית נעצרת, אבל עם הודעה ברורה. זה בדיוק המטרה כשמדובר בבאג.
Raising without catching: the program stops, but with a clear message. That's exactly the point for a bug.
def set_rating(stars):
if not 1 <= stars <= 5:
raise ValueError(f"rating must be 1-5, got {stars}")
set_rating(9)Traceback (most recent call last):
File "/Users/you/python-course/raise_demo.py", line 5, in <module>
set_rating(9)
~~~~~~~~~~^^^
File "/Users/you/python-course/raise_demo.py", line 3, in set_rating
raise ValueError(f"rating must be 1-5, got {stars}")
ValueError: rating must be 1-5, got 9ValueError: 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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
raise עוצר בכוונה כשמשהו לא הגיוני.
raise stops on purpose when something makes no sense.
def set_age(n):
if n < 0:
raise ValueError("age can't be negative")
return n
print(set_age(8))
try:
set_age(-2)
except ValueError as e:
print("Oops:", e)8 Oops: age can't be negative
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06סוגי החריגות הנפוציםThe common exception types
שווה להכיר את החריגות הנפוצות, כי הן חוזרות שוב ושוב. except ... as e שומר את החריגה במשתנה, ואפשר להדפיס את ההודעה שלה.
It's worth knowing the common exceptions, because they come up again and again. except ... as e stores the exception in a variable so you can print its message.
| שגיאהError | מתיWhen | דוגמהExample |
|---|---|---|
ValueError | ערך לא מתאיםWrong value | int("abc") |
TypeError | טיפוס לא מתאיםWrong type | "a" + 1 |
KeyError | מפתח חסר במילוןMissing dict key | d["x"] |
IndexError | אינדקס מחוץ לטווחIndex out of range | [1][5] |
NameError | שם לא מוגדרUndefined name | pritn(1) |
FileNotFoundError | קובץ לא קייםMissing file | open("x.txt") |
ZeroDivisionError | חילוק באפסDivision by zero | 1 / 0 |
AttributeError | אין מתודה כזוNo such method | 5.upper() |
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}")ValueError invalid literal for int() with base 10: 'abc' TypeError can only concatenate str (not "int") to str KeyError 'x' IndexError list index out of range ZeroDivisionError division by zero
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סוגי חריגות הם כמו נורות אזהרה בלוח המחוונים של מכונית: כל נורה מסמנת בעיה אחרת, ומי שמכיר אותן יודע מיד לאן להסתכל.
Exception types are like warning lights on a car's dashboard: each one marks a different problem, and if you know them you know where to look.
מנסים לתפוס שגיאת תחביר. SyntaxError קורית לפני שהקוד בכלל רץ, ולכן try לא עוזר.
Trying to catch a syntax error. SyntaxError happens before the code even runs, so try doesn't help.
try:
print("hi"
except SyntaxError:
print("caught") File "/Users/you/python-course/types_demo.py", line 2
print("hi"
^
SyntaxError: '(' was never closedSyntaxError: '(' 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.סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.