Python: Exception Handling

Write code that recovers gracefully when things go wrong. Exception handling separates the normal flow of logic from error recovery, keeping your programs robust and readable.

Syntax Errors vs Exceptions

Python errors fall into two broad categories. A SyntaxError is detected by the interpreter before any code runs - it means the code itself is written incorrectly and Python cannot even parse it. An Exception (runtime error) occurs while the program is executing. Exceptions are the kind you can catch and recover from; syntax errors must be fixed in the source code.

Two Categories of Error

Only exceptions can be caught with try/except. Syntax errors must be fixed in the editor.

  • SyntaxError: missing colon, unmatched bracket, bad indentation
  • Exception: ZeroDivisionError, KeyError, TypeError, and hundreds more
  • All built-in exceptions inherit from the base Exception class
  • try/except only catches exceptions, never syntax errors

The Distinction in Practice

Python

One fails before running; the other fails at runtime.

try and except Block

The try block contains the code that might raise an exception. Theexcept block runs only if an exception occurs. If no exception is raised, the except block is skipped entirely. You can catch a specific exception type or use a bareexceptto catch everything, though a bare except is generally discouraged.

Basic try/except

Python

Catching a division by zero without crashing.

Handling Specific and Multiple Exceptions

Always be as specific as possible when catching exceptions. CatchingExceptionor using a bare exceptswallows unrelated errors and makes bugs very hard to track down. You can handle multiple exception types in one clause by grouping them in a tuple, or write separate clauses that take different recovery actions.

Multiple Exception Handlers

Python

Providing different responses for different failure modes.

else and finally Blocks

The else block executes only when the try block finishes without raising an exception. This is useful for code that should run on success but does not belong in the try block itself. The finallyblock always runs regardless of what happened. It is the right place to release resources: close connections, release locks, or flush buffers.

Full try/except/else/finally

Python

The complete structure for safe resource management.

raise and Re-raising Exceptions

Use raiseto throw an exception intentionally, for example when validating input. Inside an except block, a bare raisere-raises the current exception, preserving the original traceback. This is useful when you want to log the error and still let it propagate up the call stack.

Raising and Re-raising

Python

Signalling errors and letting them propagate.

Exception Chaining with raise from

When you catch one exception and raise a different one, Python can link them together so the traceback shows both. Useraise NewError(...) from originalto make the chain explicit. This keeps domain-specific errors clean at the API surface while preserving the underlying cause for debugging.

Chaining Exceptions

Python

Translating low-level errors into domain-specific ones.

Common Built-in Exceptions

Python ships with a rich hierarchy of built-in exceptions. Knowing which exception corresponds to which error condition helps you write precise handlers and informative error messages.

Exception Reference

The most frequently encountered exceptions in everyday Python code.

  • ValueError: right type, wrong value (e.g., int("abc"))
  • TypeError: operation applied to the wrong type (e.g., 1 + "a")
  • IndexError: index out of range for a list or tuple
  • KeyError: key not found in a dictionary
  • FileNotFoundError: open() called on a non-existent file
  • ZeroDivisionError: division or modulo by zero
  • AttributeError: accessing a non-existent attribute or method
  • ImportError / ModuleNotFoundError: module cannot be imported
  • RecursionError: maximum recursion depth exceeded
  • OverflowError: result too large for a numeric type

Triggering Common Exceptions

Python

Seeing each exception in a minimal example.

Custom Exception Classes

You can define your own exception classes by inheriting fromExceptionor one of its subclasses. Custom exceptions allow you to model errors specific to your application domain, making error messages clearer and allowing callers to catch only the errors they know how to handle.

Domain-Specific Exceptions

Python

Building a small hierarchy for a payments module.

Assertions with assert

The assert statement tests a condition and raises anAssertionErrorif it is false. Assertions are primarily a debugging tool for catching programmer errors early, not for validating user input. They can be disabled globally by running Python with the -O(optimize) flag, so never use them for logic your production code depends on.

assert vs raise

Use assert for internal sanity checks; use raise for user-facing validation.

  • assert condition, "optional message" is the full syntax
  • Assertions can be turned off with python -O, so they are not a security mechanism
  • Ideal for: checking preconditions, postconditions, and invariants during development
  • Never use assert to validate user input or external data

Assertions in Practice

Python

Validating internal assumptions during development.

Quiz - Test Your Knowledge

Work through these eight questions covering the full exception handling toolkit. Pay attention to the execution order of try, except, else, and finally, and to which exception types correspond to which errors.

Knowledge Check

1. What is the difference between a SyntaxError and a RuntimeError (Exception)?

2. When does the else block of a try statement execute?

3. Which block is guaranteed to run whether or not an exception is raised?

4. What does "raise from" do when chaining exceptions?

5. Which exception is raised when you access a dictionary with a key that does not exist?

6. How do you create a custom exception class in Python?

7. What happens when an assert statement fails?

8. Which is the correct way to catch multiple specific exceptions in one line?