Tutorials Python Python try except finally
Ch 41 / 58
Python Intermediate 13 min read Chapter 41 of 58

Python try / except / finally

Chapter 40 introduced exceptions — this chapter goes deeper. Here you'll master every nuance of the four-clause structure: exactly when each runs, how exceptions propagate through nested try blocks, how to write cleanup code that is bulletproof, how to suppress specific exceptions elegantly with contextlib.suppress, how to write exception-safe resource management, and the fine details that separate beginner error handling from professional-grade Python code.

What you'll learn in this chapter
All four clauses — exact execution rules
Exception propagation through call stacks
Nested try blocks — inner vs outer handling
Suppressing exceptions — contextlib.suppress
finally with return, break and continue
Writing exception-safe, production-grade code
Advertisement

All Four Clauses — Exact Execution Rules

A complete try statement can have up to four clauses. Understanding exactly when each runs — in every scenario — is fundamental to writing correct error handling code.

Four-clause structure — when each runs
try: Always attempted first
Contains the risky code. Execution stops at the first exception and jumps to the matching except. If no exception, skips all except clauses.
result = 10 / x ← may raise ZeroDivisionError
except: Only if a matching exception was raised
Handles the exception. Can have multiple except clauses — Python tries top-to-bottom. If none match, the exception propagates.
except ZeroDivisionError as e: handle(e)
else: Only if NO exception was raised in try
Runs only on success. Exceptions raised here are not caught by the preceding except clauses — they propagate normally.
else: save_result(result) ← success-only code
finally: ALWAYS — exception or not, caught or not
Guaranteed cleanup. Runs even if there's a return, break, continue, or uncaught exception. Use for releasing resources.
finally: conn.close() ← ALWAYS runs
Python — all_clauses_demo.py
def demo(x):
    print(f"\n--- demo({x}) ---")
    try:
        print("try: executing")
        result = 10 / x
        print(f"try: got {result}")
    except ZeroDivisionError:
        print("except: caught ZeroDivisionError")
    else:
        print(f"else: success! result = {result}")
    finally:
        print("finally: ALWAYS runs")

demo(2)
# try: executing
# try: got 5.0
# else: success! result = 5.0   ← no exception
# finally: ALWAYS runs

demo(0)
# try: executing
# except: caught ZeroDivisionError  ← exception handled
# [else skipped]
# finally: ALWAYS runs

Exception Propagation — How Exceptions Travel

When an exception is raised and not caught in the current function, it propagates up the call stack — looking for a matching except clause in the calling function, then its caller, and so on. If it reaches the top without being caught, Python prints a traceback and the program ends.

Exception propagation up the call stack
inner() raises ValueError ← exception starts here
▲
no except in inner() → propagates to caller
middle() — no matching except → propagates further
▲
still not caught → propagates to main()
main() — except ValueError: ✅ caught here
Python — propagation.py
def inner():
    print("inner: raising ValueError")
    raise ValueError("bad value from inner()")

def middle():
    print("middle: calling inner()")
    inner()                            # exception propagates through here
    print("middle: this line never runs")

def main():
    try:
        middle()
    except ValueError as e:
        print(f"main: caught — {e}")  # caught here, 2 levels up!

main()
# inner: raising ValueError
# middle: calling inner()
# main: caught — bad value from inner()

# Reading the traceback (innermost frame last)
# Traceback (most recent call last):
#   File "...", line ..., in main     ← outermost
#     middle()
#   File "...", line ..., in middle   ← middle frame
#     inner()
#   File "...", line ..., in inner    ← where it was raised
#     raise ValueError("bad value from inner()")
# ValueError: bad value from inner()

Nested try Blocks

You can nest try blocks inside each other — Python handles exceptions at the innermost matching level first. Nested try blocks are useful when different parts of an operation need different error handling strategies.

Python — nested_try.py
# ── Basic nested try ──────────────────────────────────
try:                            # outer
    try:                        # inner
        raise ValueError("inner error")
    except ValueError:
        print("inner except: handled")
        raise RuntimeError("from handler")  # propagates to outer
except RuntimeError as e:
    print(f"outer except: {e}")

# ── Real-world: open file, then parse ─────────────────
def load_users(path):
    try:                                # outer: file access
        with open(path, encoding="utf-8") as f:
            raw = f.read()
    except FileNotFoundError:
        print(f"File not found: {path}")
        return []
    except PermissionError:
        print(f"No permission: {path}")
        return []

    try:                                # inner: parse JSON
        import json
        users = json.loads(raw)
        return users
    except json.JSONDecodeError as e:
        print(f"Invalid JSON in {path}: {e}")
        return []

# ── Exception raised in except ────────────────────────
try:
    x = int("bad")
except ValueError:
    try:
        fallback()                  # this might also raise
    except Exception as e2:
        print(f"Fallback also failed: {e2}")
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

finally Nuances — return, break and continue

The finally clause runs before any return, break, or continue in try/except — which creates some surprising behaviours. Understanding these guarantees makes your cleanup code bulletproof.

Python — finally_nuances.py
# ── finally runs before return ────────────────────────
def get_value():
    try:
        return "from try"
    finally:
        print("finally runs BEFORE the return!")

print(get_value())
# finally runs BEFORE the return!
# from try

# ── finally return OVERRIDES try return ───────────────
def tricky():
    try:
        return 10              # would return 10...
    finally:
        return 99              # ...but finally return WINS!

print(tricky())             # 99  ← finally overrides try
# ⚠️ Never use return in finally — it silently swallows exceptions!

# ── finally with an uncaught exception ────────────────
def with_uncaught():
    try:
        raise RuntimeError("boom!")
    finally:
        print("finally: cleanup runs even for uncaught exceptions")
    # RuntimeError still propagates after finally

try:
    with_uncaught()
except RuntimeError as e:
    print(f"Caught outside: {e}")

# ── finally in a loop ─────────────────────────────────
def loop_finally():
    for i in range(3):
        try:
            if i == 1: break
        finally:
            print(f"finally: i={i}")  # runs before break!

loop_finally()
# finally: i=0
# finally: i=1  ← runs before break

# ── Resource cleanup pattern (prefer with statement) ──
conn = None
try:
    conn = get_db_connection()
    result = conn.query("SELECT *")
except DatabaseError as e:
    print(f"Query failed: {e}")
finally:
    if conn is not None:
        conn.close()              # ALWAYS close the connection
Never return or raise in finally Using return or raise inside a finally block silently discards any active exception. If an exception was propagating and finally does a return, the exception disappears without any indication. This is one of Python's most surprising gotchas.

Suppressing Exceptions — contextlib.suppress

Sometimes you genuinely want to ignore a specific exception — for example, deleting a file that might not exist. The idiomatic way is contextlib.suppress() — more readable than a try/except/pass block.

Python — suppress_exceptions.py
from contextlib import suppress
import os

# ── contextlib.suppress — clean way to ignore exceptions
with suppress(FileNotFoundError):
    os.remove("temp.txt")            # silently skip if missing

# Equivalent verbose version:
try:
    os.remove("temp.txt")
except FileNotFoundError:
    pass

# Suppress multiple exception types
with suppress(FileNotFoundError, PermissionError):
    os.remove("locked_file.txt")

# ── Suppress in loops ─────────────────────────────────
files = ["a.txt", "b.txt", "c.txt"]
for path in files:
    with suppress(FileNotFoundError):
        os.remove(path)              # best-effort deletion

# ── pathlib equivalent ────────────────────────────────
from pathlib import Path
Path("temp.txt").unlink(missing_ok=True)  # Python 3.8+ — no suppress needed

# ── When NOT to suppress ──────────────────────────────
# ❌ suppress(Exception)  — too broad, hides real bugs
# ❌ suppress(BaseException)  — never do this
# ✅ suppress(FileNotFoundError)  — specific and intentional

# ── contextlib.ExitStack — dynamic context managers ──
from contextlib import ExitStack

with ExitStack() as stack:
    files = [stack.enter_context(open(f)) for f in ["a.txt", "b.txt"]]
    stack.callback(print, "All files closed!")
# All files closed when with block exits

Accessing Exception Information

Beyond catching exceptions, Python gives you rich access to exception details — the traceback, exception chain, args, and notes (Python 3.11+). This is essential for logging, debugging, and building user-friendly error messages.

Python — exception_info.py
import traceback
import sys
import logging

# ── Access exception attributes ───────────────────────
try:
    int("bad")
except ValueError as e:
    print(type(e).__name__)    # ValueError
    print(e.args)              # ("invalid literal...",)
    print(str(e))              # invalid literal for int()...
    print(e.__traceback__)     # traceback object

# ── Get traceback as string ───────────────────────────
try:
    1 / 0
except ZeroDivisionError:
    tb_str = traceback.format_exc()
    print(tb_str)              # full traceback as string

# ── logging.exception() — logs traceback automatically
try:
    risky_op()
except Exception:
    logging.exception("Unexpected error")  # logs message + traceback

# ── Exception chain attributes ────────────────────────
try:
    try:
        raise ValueError("original")
    except ValueError as e:
        raise RuntimeError("wrapped") from e
except RuntimeError as e:
    print(e.__cause__)         # ValueError("original")  ← from clause
    print(e.__context__)       # same — the original exception

# ── Exception notes (Python 3.11+) ───────────────────
try:
    e = ValueError("bad data")
    e.add_note("Hint: check input format")
    e.add_note("Hint: use ISO 8601 dates")
    raise e
except ValueError as e:
    print(e.__notes__)        # ['Hint: check input format', ...]

Production-Grade Error Handling Patterns

Here are the exception handling patterns used in Django, FastAPI, and production Python services. These go beyond basics to show how real-world code manages errors at scale:

Python — production_patterns.py
import logging
import functools
from contextlib import suppress

# ── Pattern 1: Exception decorator for service layer ──
def handle_errors(*exc_types, default=None, log=True):
    """Decorator: catch exceptions, log, return default."""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except exc_types as e:
                if log:
                    logging.error(f"{func.__name__} failed: {e}")
                return default
        return wrapper
    return decorator

@handle_errors(ValueError, TypeError, default=[])
def parse_scores(raw):
    return [int(s) for s in raw.split(",")]

print(parse_scores("90,85,92"))  # [90, 85, 92]
print(parse_scores("bad,data"))   # [] — error logged, default returned

# ── Pattern 2: Result type (EAFP with structured result)
class Result:
    def __init__(self, value=None, error=None):
        self.value = value
        self.error = error
        self.ok    = error is None

def safe_divide(a, b) -> Result:
    try:
        return Result(value=a / b)
    except (ZeroDivisionError, TypeError) as e:
        return Result(error=str(e))

r = safe_divide(10, 0)
if r.ok:
    print(r.value)
else:
    print(f"Error: {r.error}")

# ── Pattern 3: Structured exception logging ───────────
def process_request(request_id, data):
    try:
        result = validate_and_process(data)
        return {"status": "ok", "data": result}
    except ValidationError as e:
        logging.warning("Validation failed", extra={
            "request_id": request_id,
            "field": e.field,
            "error": str(e)
        })
        return {"status": "error", "message": str(e)}
    except Exception:
        logging.exception(f"Unhandled error in request {request_id}")
        return {"status": "error", "message": "Internal server error"}

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all try/except/finally examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every try/except/finally example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • try: risky code. except: runs only on exception. else: runs only on success (exceptions here propagate normally). finally: always runs regardless.
  • Exception propagation: an unhandled exception climbs the call stack looking for a matching except clause. If none is found anywhere, the program terminates with a traceback.
  • Nested try blocks: the innermost matching handler runs first. Exceptions can be caught, re-raised, or replaced with a new exception at any level.
  • finally runs before any return, break, or continue. If finally itself does a return, it overrides and silently discards any active exception.
  • Use contextlib.suppress(ExcType) as a clean, readable alternative to try/except/pass when you genuinely want to ignore a specific exception.
  • Access exception details via: type(e).__name__, e.args, str(e), e.__cause__, e.__traceback__. Use traceback.format_exc() for the full traceback as a string.
  • Use logging.exception("msg") to log an error message along with the full traceback automatically.
  • Production patterns: exception decorators, Result types, structured logging with context, retry wrappers, and contextlib.ExitStack for dynamic cleanup.
⚡
Free Resource
Download our Python try/except/finally Cheat Sheet
All clauses, propagation, nested try, finally nuances, suppress, exception info & production patterns — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

Exceptions raised inside the else clause are not caught by the preceding except clauses in the same try statement. They propagate normally up the call stack, just like any unhandled exception.

This is actually a key reason to use else instead of just putting success code directly after the try block — it clearly separates "code that might raise the anticipated exception" from "success-only code whose exceptions should propagate unfiltered".

✓ Answer

contextlib.suppress(ExcType) is a context manager that silently suppresses the specified exception types. It's the idiomatic alternative to try/except/pass:

# Verbose:
try:
    os.remove("file.txt")
except FileNotFoundError: pass

# Idiomatic:
with suppress(FileNotFoundError):
    os.remove("file.txt")

Use it when you genuinely intend to ignore a specific exception — best-effort operations like optional cleanup. Never use suppress(Exception) — it's too broad.

✓ Answer

A return statement inside finally silently swallows any active exception. If an exception was propagating (either uncaught or being re-raised), a return in finally cancels it without any error message:

def oops():
    try:
        raise ValueError("bug!")
    finally:
        return "ok"  # ← ValueError silently lost!
print(oops())  # "ok" — no exception visible

The exception disappears completely — no traceback, no indication of the bug. Never put return or raise in finally.

✓ Answer

Use logging.exception("message") inside an except block. It automatically captures and logs the current exception's traceback along with your message at ERROR level:

import logging

try:
    risky_op()
except Exception:
    logging.exception("Unexpected error in risky_op")
    # logs: ERROR:root:Unexpected error in risky_op
    # + full traceback automatically included

Alternatively, get the traceback as a string with import traceback; traceback.format_exc().

✓ Answer

Exception propagation is the process by which an unhandled exception climbs up the call stack looking for a matching except clause in the calling functions. If no handler is found at any level, Python terminates the program and prints a traceback.

You can stop propagation by:

  • Having a matching except clause that handles (and doesn't re-raise) the exception.
  • Using contextlib.suppress(ExcType) for intentional silencing.
  • Avoid: using return in finally — it stops propagation but silently hides the bug.
MCQ 1 of 3
In a try/except/else/finally block, when does the else clause run?
MCQ 2 of 3
Which module provides the suppress() context manager?
MCQ 3 of 3
What does logging.exception("message") do that logging.error("message") does not?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel