Skip to content

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.

Built-in exceptions are standard error types defined in the Python standard library and form a hierarchy that lets you catch broad categories of errors or specific problems in your code.

Examples

Exceptions are typically handled using try…except blocks:

Language: 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:

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

Custom exceptions can be created by inheriting from Exception:

Language: Python
class CustomError(Exception):
    pass

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

Language: Python
if value > 100:
    raise ValueError("too big")
Python's raise: Effectively Raising Exceptions in Your Code

Course

Using raise for Effective Exceptions

In this video course, you'll learn how to raise exceptions in Python, which will improve your ability to efficiently handle errors and exceptional situations in your code. This way, you'll write more reliable, robust, and maintainable code.

intermediate python

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

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Dan Bader • Updated Dec. 2, 2026 • Reviewed by Leodanis Pozo Ramos