Tutorials Python Python Exceptions
Ch 40 / 58
Python Intermediate 13 min read Chapter 40 of 58

Python Exceptions

Errors are inevitable — a file might not exist, a network request might fail, a user might enter invalid data. Exceptions are Python's mechanism for handling these situations gracefully instead of crashing. This chapter covers the complete exception system: try/except/else/finally blocks, catching specific and multiple exceptions, the raise statement, Python's exception hierarchy, creating custom exception classes, and the real-world error handling patterns that professional Python developers use every day.

What you'll learn in this chapter
What exceptions are and why they occur
try / except / else / finally — all four clauses
Catching specific, multiple and all exceptions
raise — triggering exceptions manually
Python exception hierarchy and built-in types
Custom exception classes — best practices
Advertisement

What are Exceptions?

An exception is an event that occurs during program execution that disrupts the normal flow. Python raises exceptions automatically for errors like dividing by zero, accessing a missing dict key, opening a non-existent file, or calling a method on the wrong type. Without exception handling, your program crashes with a traceback.

Python Built-in Exception Hierarchy (most common)
BaseException
└─
Exception
← catch this, not BaseException
├─
ValueError
int("hello")
├─
TypeError
"a" + 1
├─
KeyError
d["missing"]
├─
IndexError
lst[99]
├─
AttributeError
None.upper()
├─
FileNotFoundError
open("x.txt")
├─
ZeroDivisionError
1 / 0
└─
ImportError
import missing_mod
Python — what_is_exception.py
# ❌ Without exception handling — program crashes
# print(1 / 0)   → ZeroDivisionError: division by zero
# print(int("x")) → ValueError: invalid literal for int()
# print({}["key"]) → KeyError: 'key'

# ✅ With exception handling — graceful recovery
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
# Program continues normally here

# Every exception is an object — you can inspect it
try:
    int("not a number")
except ValueError as e:
    print(type(e).__name__)     # ValueError
    print(e)                    # invalid literal for int() with base 10: 'not a number'
    print(e.args)               # ("invalid literal...",)

try / except — Catching Exceptions

The try block contains code that might raise an exception. The except block runs only if a matching exception was raised. Python stops executing the try block at the first exception and jumps to the matching except clause.

try / except / else / finally — execution flow
try: — risky code runs here
▼
exception raised? → split
except: — runs IF exception occurred
else: — runs if NO exception
▼
always runs regardless
finally: — ALWAYS runs (cleanup)
Python — try_except.py
# ── Basic try/except ──────────────────────────────────
try:
    x = int(input("Enter a number: "))
    result = 100 / x
    print(f"Result: {result}")
except ValueError:
    print("Not a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

# ── Capture the exception object ─────────────────────
try:
    data = {"name": "Alice"}
    print(data["age"])             # KeyError!
except KeyError as e:             # 'as e' captures the exception
    print(f"Missing key: {e}")    # Missing key: 'age'

# ── Catch parent exception — catches subtypes too ────
try:
    f = open("missing.txt")
except OSError as e:               # catches FileNotFoundError too
    print(f"OS error: {e}")

# ── Catch ANY exception (use sparingly!) ─────────────
try:
    risky_operation()
except Exception as e:
    print(f"Unexpected error: {type(e).__name__}: {e}")
# ⚠️ Never catch BaseException — it catches SystemExit and KeyboardInterrupt!

Catching Multiple Exceptions

You can have multiple except clauses — Python tries them top-to-bottom and runs the first match. You can also catch multiple exception types in a single tuple except (TypeError, ValueError):. More specific exceptions should always come before more general ones.

Python — multiple_exceptions.py
# ── Multiple except clauses ───────────────────────────
def safe_divide(a, b):
    try:
        return a / b
    except TypeError:               # wrong types — more specific first
        print("Both arguments must be numbers")
    except ZeroDivisionError:       # b is 0
        print("Cannot divide by zero")
    except Exception as e:         # catch-all at the end
        print(f"Unexpected: {e}")
    return None

print(safe_divide(10, 2))        # 5.0
print(safe_divide(10, 0))        # Cannot divide by zero
print(safe_divide("a", 2))       # Both arguments must be numbers

# ── Catch multiple types in one tuple ────────────────
try:
    value = int(user_input)
except (ValueError, TypeError) as e:    # one handler for both
    print(f"Invalid input: {e}")

# ── Order matters — specific before general ───────────
try:
    f = open("file.txt")
except FileNotFoundError:    # ← specific (subclass of OSError)
    print("File does not exist")
except PermissionError:     # ← also a subclass of OSError
    print("No permission to read")
except OSError as e:         # ← general (parent) at the end
    print(f"OS error: {e}")

# ── Inspect exception type dynamically ────────────────
try:
    pass
except Exception as e:
    print(type(e).__name__)   # name of the exception class
    print(isinstance(e, ValueError))  # type check
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

else & finally Clauses

The else clause runs only if the try block completed without any exception — perfect for code that should run only on success. The finally clause runs always — whether an exception occurred or not — making it ideal for cleanup (closing files, releasing locks, disconnecting from databases).

Python — else_finally.py
# ── try / except / else / finally ────────────────────
def load_config(path):
    f = None
    try:
        f = open(path, encoding="utf-8")      # may raise FileNotFoundError
        import json
        config = json.load(f)                  # may raise JSONDecodeError
    except FileNotFoundError:
        print(f"Config file not found: {path}")
        config = {}
    except json.JSONDecodeError as e:
        print(f"Invalid JSON: {e}")
        config = {}
    else:                                       # ← runs ONLY if no exception
        print(f"Config loaded: {len(config)} keys")
    finally:                                    # ← ALWAYS runs
        if f:
            f.close()
        print("Config operation complete")
    return config

# finally runs even with a return or raise in try/except
def demo_finally():
    try:
        return "from try"
    finally:
        print("finally runs before return!")

print(demo_finally())
# finally runs before return!
# from try

# ── Why else instead of putting code after try? ───────
# else only catches exceptions from try block
# putting code after try would catch NEW exceptions from that code too
try:
    result = int("42")
except ValueError:
    print("bad input")
else:
    print(f"Success: {result}")    # runs only on success
    process(result)               # process() exceptions NOT caught by above except

raise — Triggering Exceptions

You can raise exceptions intentionally with the raise statement — to signal invalid inputs, enforce preconditions, or re-raise caught exceptions. Use raise ... from ... to chain exceptions and preserve context.

Python — raise_statement.py
# ── raise with a message ─────────────────────────────
def set_age(age):
    if not isinstance(age, int):
        raise TypeError(f"age must be int, got {type(age).__name__}")
    if age < 0 or age > 150:
        raise ValueError(f"age must be 0-150, got {age}")
    return age

print(set_age(25))      # 25
# set_age(-5)        → ValueError: age must be 0-150, got -5
# set_age("old")     → TypeError: age must be int, got str

# ── Re-raise — catch, log, re-raise ──────────────────
import logging

def process(data):
    try:
        result = risky_op(data)
    except ValueError as e:
        logging.error(f"ValueError in process(): {e}")
        raise                          # ← re-raise without changing it

# ── Exception chaining with raise...from ─────────────
class DatabaseError(Exception): pass

def get_user(user_id):
    try:
        return db.query(user_id)
    except ConnectionError as e:
        raise DatabaseError("Failed to fetch user") from e
        # Original ConnectionError preserved in e.__cause__

# ── raise without arguments — re-raise current ───────
try:
    int("bad")
except ValueError:
    print("Caught and re-raising")
    raise               # re-raises the same ValueError

# ── assert — lightweight pre-condition check ─────────
def sqrt(n):
    assert n >= 0, f"sqrt requires non-negative, got {n}"
    return n ** 0.5
# sqrt(-1)  → AssertionError: sqrt requires non-negative, got -1
# Note: assert is disabled with python -O (optimised mode)

Custom Exception Classes

Custom exceptions make your code's error model explicit and professional. They allow callers to catch specific errors from your module without catching everything. The convention is to subclass Exception (or a more specific built-in) and add extra attributes for context.

Python — custom_exceptions.py
# ── Minimal custom exception ──────────────────────────
class AppError(Exception):
    """Base exception for this application."""
    pass

# ── Exception hierarchy for an app ───────────────────
class AppError(Exception):
    """Base class for all app errors."""

class ValidationError(AppError):
    """Raised when user input fails validation."""
    def __init__(self, field, message):
        self.field   = field
        self.message = message
        super().__init__(f"Validation error on '{field}': {message}")

class DatabaseError(AppError):
    """Raised when a database operation fails."""
    def __init__(self, operation, detail=""):
        self.operation = operation
        super().__init__(f"Database error during '{operation}': {detail}")

class NotFoundError(DatabaseError):
    """Raised when a record is not found."""
    def __init__(self, model, pk):
        self.model = model
        self.pk    = pk
        super().__init__("query", f"{model} with id={pk} not found")

# ── Using custom exceptions ───────────────────────────
def create_user(email, age):
    if "@" not in email:
        raise ValidationError("email", "must contain @")
    if age < 18:
        raise ValidationError("age", "must be 18+")
    print(f"User created: {email}")

try:
    create_user("aliceexample.com", 25)
except ValidationError as e:
    print(e)                           # Validation error on 'email': must contain @
    print(f"Field: {e.field}")         # Field: email
except AppError as e:               # catches any app error
    print(f"App error: {e}")

# Catch the whole hierarchy
try:
    raise NotFoundError("User", 42)
except AppError as e:             # catches DatabaseError & NotFoundError too
    print(e)

Real-World Exception Handling Patterns

Professional Python code follows consistent error handling conventions. Here are the patterns used in Django, FastAPI, and production Python services:

Python — exception_patterns.py
import logging

# ── Pattern 1: Context manager with exceptions ────────
class ManagedResource:
    def __enter__(self):
        print("Acquiring resource")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Releasing resource")
        if exc_type is ValueError:
            print(f"Handled ValueError: {exc_val}")
            return True           # suppress the exception
        return False              # propagate other exceptions

# ── Pattern 2: Retry on exception ────────────────────
import time

def retry(func, retries=3, delay=1, exceptions=(Exception,)):
    for attempt in range(retries):
        try:
            return func()
        except exceptions as e:
            print(f"Attempt {attempt+1}/{retries} failed: {e}")
            if attempt == retries - 1:
                raise
            time.sleep(delay)

# ── Pattern 3: Structured logging of exceptions ───────
def safe_process(item):
    try:
        return process(item)
    except ValueError as e:
        logging.warning(f"Validation failed for {item!r}: {e}")
        return None
    except Exception as e:
        logging.exception(f"Unexpected error processing {item!r}")
        raise                  # re-raise unexpected errors

# ── Pattern 4: Collect multiple errors ────────────────
def validate_form(data):
    errors = []
    if not data.get("name"):
        errors.append("name is required")
    if "@" not in data.get("email", ""):
        errors.append("valid email required")
    if errors:
        raise ValidationError("form", "; ".join(errors))
    return True
Exception handling best practices Be specific — catch ValueError, not Exception. Never swallow silently — at minimum log it. Don't use exceptions for flow control — use them for genuinely exceptional cases. Prefer EAFP (Easier to Ask Forgiveness than Permission) over LBYL (Look Before You Leap) in Python.

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all exception handling 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 exception example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Exceptions are Python objects — every exception is an instance of a class that inherits from BaseException. Catch from Exception, not BaseException.
  • The try block contains risky code. The except block runs if a matching exception is raised. Use except ExcType as e to capture the exception object.
  • List multiple except clauses from most specific to most general. Catch multiple types with except (TypeError, ValueError):.
  • The else clause runs only if the try block completed without raising. The finally clause always runs — use it for cleanup.
  • Use raise ExceptionType("message") to trigger exceptions. Bare raise re-raises the current exception. raise New() from original chains exceptions.
  • Create custom exceptions by subclassing Exception. Add extra attributes for context. Build a hierarchy with a base class for your module.
  • Never silently swallow exceptions with a bare except: pass. At minimum log them. Only catch exceptions you can handle meaningfully.
  • Common patterns: retry on transient errors, structured logging with logging.exception(), collect multiple errors before raising, use context managers for guaranteed cleanup.
Free Resource
Download our Python Exceptions Cheat Sheet
try/except/else/finally, raise, exception hierarchy, custom exceptions & best practices — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

else runs only if the try block completed without raising an exception. It's where you put code that should only execute on success. If an exception was caught, else is skipped.

finally always runs — whether an exception occurred or not, whether it was caught or not, even if there's a return or raise inside try/except. Use it for guaranteed cleanup (closing files, releasing locks).

✓ Answer

Exception chaining links one exception to another, preserving the original cause. Use raise NewException("msg") from original_exc.

try:
    connect_to_db()
except ConnectionError as e:
    raise DatabaseError("DB unavailable") from e

The original ConnectionError is stored in DatabaseError.__cause__. The traceback shows both — helping developers understand the full chain of events.

✓ Answer

A bare except: (or except BaseException:) catches everything — including KeyboardInterrupt (Ctrl+C), SystemExit, and MemoryError. This means:

  • The user can't stop your program with Ctrl+C
  • sys.exit() won't work
  • You hide real bugs that should crash the program

At minimum use except Exception:. Better: catch the specific exceptions you actually expect and can handle. Log unexpected ones with logging.exception() and re-raise.

✓ Answer

Define a base exception for your module, then subclass it for specific errors:

class AppError(Exception): pass       # base
class NotFoundError(AppError): pass    # specific
class ValidationError(AppError): pass # specific

# Callers can catch any level:
except NotFoundError: ...     # very specific
except AppError: ...          # any app error

This lets callers catch exactly what they can handle — specific subclasses for targeted handling, or the base class to catch all errors from your module.

✓ Answer

LBYL (Look Before You Leap) — check before acting:

if "key" in data:        # check first
    print(data["key"])

EAFP (Easier to Ask Forgiveness than Permission) — try then handle:

try:
    print(data["key"])      # just do it
except KeyError: ...

Python's culture prefers EAFP — it's more Pythonic, avoids race conditions, and often faster. However, LBYL is appropriate for cases where the check is cheap and the action is expensive or irreversible.

MCQ 1 of 3
Which clause of a try block runs only if no exception was raised?
MCQ 2 of 3
Which exception is raised when you try to access a dictionary key that doesn't exist?
MCQ 3 of 3
What does a bare raise statement (with no arguments) do inside an except block?

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