Python · Module 06: Modules, Files & Error HandlingTutorial 18 of 30
All Tutorials·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Syntax Errors vs. Exceptions (Safety-Net Analogy)

  • Syntax Error: Your code breaks Python's grammar (if x == 5 missing :). 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), or int("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!

Visual: Complete `try / except / else / finally` Execution Flowchart
try:Run risky codeexcept ValueError:Runs ONLY if an error occurredelse:Runs ONLY if NO error occurredfinally:ALWAYS runs (cleanup!)
PYTHON
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:

  1. Last line: Tells you what went wrong (KeyError: 'email', ZeroDivisionError: division by zero).
  2. 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

  1. Always catch SPECIFIC exceptions (except ValueError:), never a bare except: (which accidentally swallows KeyboardInterrupt and hides real bugs!).
  2. Keep try: blocks tiny — only wrap the 1–2 lines that can actually fail.
  3. Use raise to fail fast on invalid inputs and define custom exception classes for domain errors:
PYTHON
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

Tracing Exception Handling on Bad Input
Interactive Line-by-Line Execution Trace · Step 1 of 4
1→raw = "twenty"
2try:
3 num = int(raw)
4except ValueError:
5 num = 0
6finally:
7 print(f"Final num = {num}")
Variables in Memory
raw"twenty"str
Console Output
(nothing printed yet)
What just happened: User typed the word "twenty" instead of digits.

Quick Quiz: Module 6.3 — Exception Handling

Q1.When does the `else:` block in a `try / except / else / finally` statement run?
Q2.Why should you avoid writing a bare `except:` with no exception type?
Q3.Where should you look FIRST when reading a Python traceback?

Keep Exploring: Related Lessons & Tools

All Courses →