Introduction
Exception handling is a crucial aspect of writing robust Python code. It allows you to gracefully handle errors and exceptions that may occur during the execution of your program. In this guide, we'll explore how to use try
, except
, and finally
blocks to handle exceptions effectively, with sample code.
The Try-Except Block
The try
block is used to enclose the code that might raise an exception. If an exception occurs within the try
block, Python will jump to the corresponding except
block to handle the exception. For example:
try:
result = 10 / 0 # Division by zero
except ZeroDivisionError:
print("Error: Division by zero")
Multiple Except Blocks
You can have multiple except
blocks to handle different types of exceptions. For example:
try:
file = open("nonexistent.txt", "r")
except FileNotFoundError:
print("Error: File not found")
except PermissionError:
print("Error: Permission denied")
The Finally Block
The finally
block is used to execute code that should run regardless of whether an exception occurred or not. It's often used for cleanup operations. For example:
try:
result = 10 / 0 # Division by zero
except ZeroDivisionError:
print("Error: Division by zero")
finally:
print("Execution completed.")
Custom Exception Handling
You can define your own custom exceptions and use them for specific error handling. For example:
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom exception")
except CustomError as e:
print(f"Custom Error: {e}")
Conclusion
Exception handling is a powerful tool for dealing with unexpected situations in your Python code. With try
, except
, and finally
blocks, you can gracefully handle errors and ensure your program's stability and reliability.