1.3.5Python Intermediate

Exception handling — try, except (specific), else, finally

1,595 words7 min readdifficulty · medium5 backlinks

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()
Figure — Exception handling — try, except (specific), else, finally

HOW does the control flow actually move?


Specific vs bare except


Worked examples


Flashcards

When does the else block of a try statement run?
Only if the try block completed with no exception raised.
When does finally run?
Always — whether or not an exception occurred, was caught, or even if return/break/continue is used.
Why prefer except ValueError over a bare except:?
Bare except also swallows bugs (NameError), Ctrl-C (KeyboardInterrupt) and SystemExit, hiding real problems. Catch the narrowest exception you can handle.
If a try body raises at statement SkS_k, what happens to Sk+1S_{k+1}?
It is skipped; Python jumps straight to matching except clause.
Does except ParentError catch ChildError (a subclass)?
Yes — except matches the listed class and all its subclasses. So order child-first, parent-last.
Why put only the risky line inside try and the rest in else?
So an error in the success-handling code isn't accidentally caught by your except, which would mask a different bug.
How do you access the exception object?
except SomeError as e: binds it to e.
What does except (A, B): mean?
Catch exception A or B (a tuple of types) with the same handler.

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

raised inside

abandons rest, jumps to

matches via isinstance

no exception then run

no clause matches

nobody catches

always after

always after

always after

motivates

Exception object

try block

except SpecificError

else block

finally block

Propagate up stack

Traceback crash

Keep try region small

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.

Go deeper — visual, from zero

Test yourself — Python Intermediate

Connections