Exception handling — try, except (specific), else, finally
WHY does this exist?
An exception is an object Python raises (throws) when something abnormal happens. If nobody catches it, it propagates up the call stack until the program crashes with a traceback.
WHAT are the four blocks?
try:
risky() # WHAT: the dangerous bit
except ValueError: # WHAT: handle a SPECIFIC error
handle()
else: # WHAT: ran only if try succeeded
on_success()
finally: # WHAT: cleanup, always
cleanup()
HOW does the control flow actually move?
Specific vs bare except
Worked examples
Flashcards
When does the else block of a try statement run?
try block completed with no exception raised.When does finally run?
return/break/continue is used.Why prefer except ValueError over a bare except:?
If a try body raises at statement , what happens to ?
Does except ParentError catch ChildError (a subclass)?
Why put only the risky line inside try and the rest in else?
How do you access the exception object?
except SomeError as e: binds it to e.What does except (A, B): mean?
Recall Feynman: explain to a 12-year-old
Imagine you're cooking from a recipe (try). If a step goes wrong — you drop an egg — you don't keep blindly following the recipe. You jump to a "what to do if eggs break" note (except). If cooking went perfectly, you do the "now plate the food" step (else). And no matter what — burnt or perfect — you always wash the dishes at the end (finally). except egg-broke is specific: it doesn't fire if the oven caught fire, that's a different emergency.
Connections
- Raising exceptions — raise and custom exception classes
- The exception class hierarchy — BaseException, Exception, LookupError
- Context managers — with statement and __enter__/__exit__ (often replaces
try/finally) - File handling in Python
- Debugging and tracebacks
- Logging vs printing errors
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Dekho, exception handling ka matlab hai ki agar code chalte chalte koi galti aa jaye to program crash na ho, balki hum usko gracefully sambhaal lein. try block mein wo line daalte hain jo risky hai — jaise int("abc") ya file open karna. Agar koi error aaya, Python try ke baaki statements chhod ke seedha matching except block mein jump kar jaata hai. Isliye hamesha specific except likho, jaise except ValueError, taaki tum sirf wahi error pakdo jise tum samajhte ho — except: khaali likhne se tumhare apne typo wale bugs bhi chhup jaate hain aur ghanton debug karte raho.
else block tab chalta hai jab try mein koi error nahi aaya — yani success ka path. Iska fayda yeh hai ki tum sirf risky line ko try ke andar rakhte ho, aur success ka kaam else mein, taaki uska error galti se pakda na jaaye. Aur finally to hamesha chalta hai — error aaye ya na aaye, return ho ya break — cleanup ke liye perfect, jaise file band karna ya connection close karna.
Yaad rakho ek important rule: agar tum multiple except likh rahe ho, to child (specific) exception pehle, parent (general) baad mein — warna parent sab kuch pehle hi pakad lega aur child kabhi nahi chalega. Yeh chhoti si baat exams aur real projects dono mein bahut common galti hai.