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 try
…except
blocks:
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:
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
:
class CustomError(Exception):
pass
You can trigger exceptions (built-in or custom) with the raise
statement:
if value > 100:
raise ValueError("too big")
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Python's raise: Effectively Raising Exceptions in Your Code (Tutorial)
- Exceptions, Logging, and Debugging (Learning Path)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Using raise for Effective Exceptions (Course)
- Python's raise: Effectively Raising Exceptions in Your Code (Quiz)
By Dan Bader • Updated Jan. 14, 2025