Python Tutorial 0/52 lessons ~6 min read Lesson 34

    Exception Handling

    Use try / except / else / finally.

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Use try / except / else / finally. Catch specific exceptions, not bare except:. Define custom exception classes for your domain.

    Understanding the topic

    Core concepts to understand:

    • try / except / else / finally
    • Catch specific exceptions: except ValueError:
    • raise ... from e chains exceptions.
    • Custom exceptions inherit from Exception.

    Syntax reference

    Visual flow / code:

    python
    class PaymentError(Exception):
    """Domain-specific exception."""
    def charge(amount: float) -> None:
    try:
    if amount <= 0:
    raise ValueError("amount must be positive")
    gateway_call(amount)
    except ValueError as e:
    raise PaymentError("invalid amount") from e
    except ConnectionError:
    logger.exception("Gateway down")
    raise
    else:
    logger.info("OK")
    finally:
    cleanup()

    Execution workflow

    1Exception Handling Workflow
    1 / 4

    Step 1

    try / except / else / finally

    Apply this step while implementing exception handling in real code.

    Real-world use

    Custom exception types let upstream code distinguish 'card declined' from 'gateway down' without parsing strings — essential in microservices.

    Best practices

    • Catch specific exceptions only.
    • Use raise ... from to preserve cause.
    • Log before re-raise.

    Common mistakes

    • except: swallows KeyboardInterrupt, SystemExit — never use bare except.

    Hands-on exercise

    Interview preparation — practice these questions:

    • try/except/else/finally — when does else run?
    • Why chain exceptions?
    • EAFP vs LBYL?

    Summary

    In summary: Be specific; chain causes. EAFP is Pythonic.

    Ready to mark this lesson complete?Track your journey across the entire course.