Exception handling is a programming construct that allows you to gracefully handle errors and unexpected situations in your Python programs. Exceptions occur when something goes wrong during the execution of a program, such as division by zero, file not found, etc.
Handling Exceptions
In Python, you can use try
, except
, else
, and finally
blocks to handle exceptions. Here’s an example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero!")
else:
print("No exceptions occurred.")
finally:
print("This block always executes.")
In this example, if a ZeroDivisionError
occurs (i.e., division by zero), the code inside the except
block will be executed. If no exceptions occur, the code inside the else
block will be executed. The finally
block always executes, regardless of whether an exception occurred or not.
Raising Exceptions
You can also raise exceptions manually using the raise
statement. Here’s an example:
x = -1
if x < 0:
raise ValueError("Value must be positive.")
This will raise a ValueError
with the message “Value must be positive.”
Handling Different Types of Exceptions
You can use multiple except
blocks to handle different types of exceptions. Here’s an example:
try:
file = open("data.txt", "r")
contents = file.read()
except FileNotFoundError:
print("File not found!")
except IOError:
print("Error reading file!")
finally:
file.close()
Understanding how to handle exceptions is essential for writing robust and reliable Python programs. In the next chapter, we’ll explore object-oriented programming (OOP) in Python, which allows you to organize code into classes and objects.