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
    Interview Q&A included

    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

    try / except / else…

    try / except / else / finally

    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.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestiontry/except/else/finally — when does else run?+

    Answer

    The else block runs only if the try block finished without raising an exception, and it runs before finally. Exceptions raised in else are not caught by the preceding except clauses. Putting code in else keeps the try block small so you only catch errors from the operation you intended to guard. finally always runs afterward.

    Follow-up

    What happens if finally contains a return?
    2IntermediateQuestionWhy chain exceptions?+

    Answer

    Chaining preserves the original cause when you raise a different exception, so the traceback shows both. Use raise NewError(...) from err to set __cause__ explicitly; raising inside an except block chains implicitly through __context__. This lets you expose a clean domain-level error without losing the low-level root cause for debugging.

    Follow-up

    What does raise ... from None do?
    3IntermediateQuestionEAFP vs LBYL?+

    Answer

    EAFP means Easier to Ask Forgiveness than Permission: try the operation and handle the exception, such as try: d[key] except KeyError. LBYL means Look Before You Leap: check conditions first, such as if key in d. EAFP is idiomatic in Python and avoids race conditions between the check and the use, but LBYL can be clearer when failures are common or exceptions would be expensive.

    Follow-up

    Where does EAFP cause problems with file operations?

    Summary

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

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