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:
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:
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:
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
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.
For additional information on related topics, take a look at the following resources:
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Working With Python's Built-in Exceptions (Course)
- Python's raise: Effectively Raising Exceptions in Your Code (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Exceptions, Logging, and Debugging (Learning Path)
- Python's raise: Effectively Raising Exceptions in Your Code (Quiz)
- Python Exceptions: An Introduction (Quiz)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.