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.
ExamplesExceptions 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}")
Copied!
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
Copied!
Custom exceptions can be created by inheriting from Exception
:
class CustomError(Exception):
pass
Copied!
You can trigger exceptions (built-in or custom) with the raise
statement:
if value > 100:
raise ValueError("too big")
Copied! Related Resources
Tutorial
Python Exceptions: An IntroductionIn 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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4