6.3 Exception Handling (try/except/else/finally) & Reading Tracebacks
Turn scary red crashes into graceful recovery! Master try/except/else/finally flowcharts, catch specific exceptions cleanly, raise custom errors, and read Python tracebacks like a senior engineer.
1. Syntax Errors vs. Exceptions (Safety-Net Analogy)
- Syntax Error: Your code breaks Python's grammar (
if x == 5missing:). Python refuses to even start. - Exception (Runtime Error): Your grammar is valid, but something goes wrong while running — dividing by zero (
ZeroDivisionError), missing file (FileNotFoundError), orint("abc")(ValueError).
Without exception handling, one bad user input crashes your entire program. try / except acts like a safety net so your program can recover gracefully!
def parse_age(raw_text):
try:
age = int(raw_text)
except ValueError:
print(f"Invalid number: {raw_text!r}")
return None
else:
print("Parsed cleanly!") # Runs ONLY if try succeeded!
return age
finally:
print("Validation finished.") # ALWAYS runs!
2. How to Read a Python Traceback in 5 Seconds
Freshers often panic when they see 15 lines of red text. Always read a Python traceback from the BOTTOM UP:
- Last line: Tells you what went wrong (
KeyError: 'email',ZeroDivisionError: division by zero). - Line right above it: Tells you the exact file name, line number, and code in your project where it crashed!
3. Golden Rules of Clean Exception Handling
- Always catch SPECIFIC exceptions (
except ValueError:), never a bareexcept:(which accidentally swallowsKeyboardInterruptand hides real bugs!). - Keep
try:blocks tiny — only wrap the 1–2 lines that can actually fail. - Use
raiseto fail fast on invalid inputs and define custom exception classes for domain errors:
class InsufficientFundsError(Exception):
"""Raised when a withdrawal exceeds the available balance."""
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("Withdrawal amount must be positive.")
if amount > balance:
raise InsufficientFundsError(f"Short by {amount - balance}")
return balance - amount
4. Interactive Trace: try / except / else / finally in Action
Quick Quiz: Module 6.3 — Exception Handling
Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.