נבנה על ידיBuilt by Ariel Yohimovich

חזרה למפגשBack
PythonPython

שגיאות ו-try/exceptErrors & try/except

מפגש 11: איך קוראים Traceback, סוגי חריגות, try/except/else/finally ו-raise.Session 11: How to read a traceback, exception types, try/except/else/finally and raise.

מה נעשה היוםToday's plan

  • קריאת TracebackReading tracebacks
  • try/excepttry/except
  • לולאת קלטInput loop
  • else/finallyelse/finally
  • raiseraise
  • סוגי חריגותException types
נושאTopic 1

קריאת TracebackReading tracebacks

לקרוא Traceback ארוךReading a long traceback

אנלוגיהAnalogy

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.
נושאTopic 2

try/excepttry/except

try / except: לתפוס במקום לקרוסtry / except: catch instead of crash

  • try: קוד שעלול להיכשלtry: code that might fail
  • except ValueError: מה עושים אם נכשלexcept ValueError: what to do if it fails
  • תופסים סוג מסוים, לא הכולCatch a specific type, not everything

אנלוגיהAnalogy

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.

טעות נפוצהCommon mistake

try_demo.py
try:
    pages = int("lots")
except ZeroDivisionError:
    print("caught")
מה Python עונהWhat Python says
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.
נושאTopic 3

לולאת קלטInput loop

לנסות שוב עד שמצליחיםRetry until it works

  • while True + try + breakwhile True + try + break
  • ההודעה אומרת מה לתקןThe message says what to fix
  • קלט שגוי לא מפיל את התוכניתBad input no longer crashes

אנלוגיהAnalogy

זה כמו קופאית שמבקשת שוב את הקוד של כרטיס האשראי, ומסבירה מה היה לא בסדר, במקום לסגור את החנות.It's like a cashier asking for the card PIN again and explaining what was wrong, instead of closing the shop.
נושאTopic 4

else/finallyelse/finally

else ו-finallyelse and finally

  • else: רץ אם לא הייתה שגיאהelse: runs if there was no error
  • finally: רץ תמידfinally: always runs
  • כמה except לסוגים שוניםSeveral except for different types

אנלוגיהAnalogy

finally הוא כמו לכבות את האור כשיוצאים מהחדר: עושים את זה תמיד, לא משנה אם הפגישה הצליחה או התפוצצה.finally is like switching the light off when leaving a room: you always do it, whether the meeting went well or blew up.

טעות נפוצהCommon mistake

else_finally.py
pages = int("x")
except ValueError:
    pages = 0
מה Python עונהWhat Python says
SyntaxError: invalid syntax
SyntaxError: invalid syntax: except חייב לבוא מיד אחרי בלוק try.SyntaxError: invalid syntax: except must come right after a try block.
נושאTopic 5

raiseraise

raise: לזרוק שגיאה בעצמכםraise: throw an error yourself

  • raise ValueError("הסבר")raise ValueError("message")
  • עוצר נתונים לא חוקיים מוקדםStops invalid data early
  • הקורא מחליט איך לטפלThe caller decides how to handle it

אנלוגיהAnalogy

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.
נושאTopic 6

סוגי חריגותException types

סוגי החריגות הנפוציםThe common exception types

  • ValueError, TypeError, KeyError, IndexErrorValueError, TypeError, KeyError, IndexError
  • as e נותן את ההודעהas e gives the message
  • type(e).__name__ נותן את השםtype(e).__name__ gives the name

אנלוגיהAnalogy

סוגי חריגות הם כמו נורות אזהרה בלוח המחוונים של מכונית: כל נורה מסמנת בעיה אחרת, ומי שמכיר אותן יודע מיד לאן להסתכל.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.

טעות נפוצהCommon mistake

types_demo.py
try:
    print("hi"
except SyntaxError:
    print("caught")
מה Python עונהWhat Python says
SyntaxError: '(' was never closed
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.

מלמטה למעלהBottom to top

השורה האחרונה: סוג והסברLast line: type and message

השורות מעליה: מחסנית הקריאותLines above: the call stack

try: קוד שעלול להיכשלtry: code that might fail

except ValueError: מה עושים אם נכשלexcept ValueError: what to do if it fails

תופסים סוג מסוים, לא הכולCatch a specific type, not everything

while True + try + breakwhile True + try + break

ההודעה אומרת מה לתקןThe message says what to fix

קלט שגוי לא מפיל את התוכניתBad input no longer crashes

else: רץ אם לא הייתה שגיאהelse: runs if there was no error

finally: רץ תמידfinally: always runs

כמה except לסוגים שוניםSeveral except for different types

raise ValueError("הסבר")raise ValueError("message")

עוצר נתונים לא חוקיים מוקדםStops invalid data early

הקורא מחליט איך לטפלThe caller decides how to handle it

מה למדנוWhat we learned

  • מלמטה למעלהBottom to top
  • try: קוד שעלול להיכשלtry: code that might fail
  • while True + try + breakwhile True + try + break
  • else: רץ אם לא הייתה שגיאהelse: runs if there was no error
  • raise ValueError("הסבר")raise ValueError("message")
  • ValueError, TypeError, KeyError, IndexErrorValueError, TypeError, KeyError, IndexError

עכשיו לתרגולNow, practice

5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

נבנה על ידיBuilt by Ariel Yohimovich