exception

An exception in Python is an event that occurs during program execution that disrupts the normal flow of instructions. When Python encounters an error, it creates an exception object containing information about what went wrong and where.

Exceptions are typically handled using tryexcept blocks:

Python
try:
    # Code that might raise an exception
    result = 10 / user_input
except ZeroDivisionError:
    # Code to handle the specific exception
    print("Cannot divide by zero")
except Exception as e:
    # Code to handle any other exception
    print(f"An error occurred: {e}")

The optional finally clause executes regardless of whether an exception occurred:

Python
try:
    file = open('data.txt')
    # Process file
except FileNotFoundError:
    print("File not found")
finally:
    file.close()  # Always closes the file

Custom exceptions can be created by inheriting from Exception:

Python
class CustomError(Exception):
    pass

You can trigger exceptions (built-in or custom) with the raise statement:

Python
if value > 100:
    raise ValueError("too big")

Tutorial

Python Exceptions: An Introduction

In this beginner tutorial, you'll learn what exceptions are good for in Python. You'll see how to raise exceptions and how to handle them with try ... except blocks.

basics python

For additional information on related topics, take a look at the following resources:


By Dan Bader • Updated Jan. 14, 2025