מפגש 11: איך קוראים Traceback, סוגי חריגות, try/except/else/finally ו-raise.Session 11: How to read a traceback, exception types, try/except/else/finally and raise.
איך קוראים Traceback, סוגי חריגות, try/except/else/finally ו-raise. בסוף המפגש מוסיפים צעד לפרויקט המלווה.How to read a traceback, exception types, try/except/else/finally and raise. At the end we add a step to the companion project.
מה נעשה היוםToday's plan
קריאת TracebackReading tracebacks
try/excepttry/except
לולאת קלטInput loop
else/finallyelse/finally
raiseraise
סוגי חריגותException types
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.
נושאTopic 1
קריאת TracebackReading tracebacks
לקרוא Traceback ארוךReading a long traceback
מלמטה למעלהBottom to top
השורה האחרונה: סוג והסברLast line: type and message
כשהשגיאה קורית בתוך פונקציה שנקראה מפונקציה אחרת, ה-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.
אנלוגיה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.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושא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
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.
אנלוגיה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.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
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.
תופסים סוג אחר ממה שקורה בפועל. ה-except לא תופס, והתוכנית עדיין נופלת.Catching a different type from what actually happens. The except doesn't catch it, and the program still crashes.
נושא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
הדפוס הכי שימושי: לולאה שמבקשת קלט עד שמגיע קלט תקין. ה-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.
אנלוגיהAnalogy
זה כמו קופאית שמבקשת שוב את הקוד של כרטיס האשראי, ומסבירה מה היה לא בסדר, במקום לסגור את החנות.It's like a cashier asking for the card PIN again and explaining what was wrong, instead of closing the shop.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
נושא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
אפשר כמה בלוקי 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).
אנלוגיה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.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצה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.
except בלי try לפניו.except without a try before it.
נושאTopic 5
raiseraise
raise: לזרוק שגיאה בעצמכםraise: throw an error yourself
עוצר נתונים לא חוקיים מוקדםStops invalid data early
הקורא מחליט איך לטפלThe caller decides how to handle it
לפעמים הקוד שלכם מגלה בעיה ש-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.
אנלוגיה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.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
type(e).__name__ נותן את השםtype(e).__name__ gives the name
שווה להכיר את החריגות הנפוצות, כי הן חוזרות שוב ושוב. 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.
אנלוגיה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.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצה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.
מנסים לתפוס שגיאת תחביר. SyntaxError קורית לפני שהקוד בכלל רץ, ולכן try לא עוזר.Trying to catch a syntax error. SyntaxError happens before the code even runs, so try doesn't help.
מלמטה למעלהBottom to top
לקרוא Traceback ארוךReading a long traceback
השורה האחרונה: סוג והסברLast line: type and message