Skip to content

Python Exception Handling: Effortlessly Mastering Exercises

[

Python Exception Handling Exercises

Exception Handling Basics

Exception handling is a crucial aspect of programming in Python. It allows us to gracefully handle errors and ensure that our programs continue running smoothly, even in the face of unexpected issues. In this tutorial, we will explore various exercises to practice exception handling in Python and improve our problem-solving skills.

Exercise 1: Handling a ZeroDivisionError

Let’s start with a simple exercise that involves handling a ZeroDivisionError. The code below calculates the average of two numbers and displays the result. However, it encounters a ZeroDivisionError when the second number is zero.

def calculate_average(num1, num2):
try:
average = (num1 + num2) / 2
print(f"The average is: {average}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
calculate_average(10, 5)
calculate_average(8, 0)

In this exercise, we use a try-except block to catch the ZeroDivisionError. If the error occurs, we display a custom error message indicating that division by zero is not allowed. Running the above code will produce the following output:

The average is: 7.5
Error: Division by zero is not allowed.

Exercise 2: Handling FileNotFoundError

Next, let’s practice handling a FileNotFoundError that can occur when working with files. Consider the following code snippet that attempts to read the contents of a file called data.txt:

def read_file(filename):
try:
with open(filename, 'r') as file:
contents = file.read()
print(contents)
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
read_file("data.txt")
read_file("sample.txt")

Here, we use a try-except block to catch the FileNotFoundError. If the file is not found, we display a custom error message indicating the file name that was not found. Running the above code will generate the following output:

Error: File 'data.txt' not found.
This is a sample file.

Advanced Exception Handling

Exercise 3: Handling Multiple Exceptions

In addition to handling individual exceptions, Python allows us to handle multiple exceptions in a single try-except block. Consider the following code snippet:

def divide_numbers(num1, num2):
try:
result = num1 / num2
print(f"The result is: {result}")
except (ZeroDivisionError, ValueError):
print("Error: Division by zero or invalid value.")
divide_numbers(10, 5)
divide_numbers(8, 0)
divide_numbers(10, 'a')

In this exercise, we catch both ZeroDivisionError and ValueError using a single except statement. If either of these exceptions occurs, we display a custom error message. Running the above code will produce the following output:

The result is: 2.0
Error: Division by zero or invalid value.
Error: Division by zero or invalid value.

Exercise 4: Handling Exceptions with Finally

Sometimes, we need to ensure that certain code always gets executed, whether an exception occurs or not. The finally block in Python allows us to accomplish this. Consider the code below:

def open_file(filename):
try:
file = open(filename, 'r')
try:
contents = file.read()
print(contents)
finally:
file.close()
print(f"File '{filename}' closed successfully.")
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
open_file("sample.txt")
open_file("data.txt")

In this exercise, we use a finally block to ensure that the file is always closed, even if an exception occurs. Running the above code will produce the following output:

This is a sample file.
File 'sample.txt' closed successfully.
Error: File 'data.txt' not found.

Exercise 5: Raising Custom Exceptions

Python also allows us to create our own custom exceptions for more tailored error handling. Consider the following example:

class NegativeNumberError(Exception):
pass
def find_square_root(number):
if number < 0:
raise NegativeNumberError("Error: Cannot find square root of a negative number.")
else:
sqrt = pow(number, 0.5)
print(f"The square root of {number} is {sqrt}.")
try:
find_square_root(-4)
find_square_root(25)
except NegativeNumberError as e:
print(e)

In this exercise, we create a custom exception called NegativeNumberError and raise it if the number passed to the find_square_root function is negative. Running the above code will generate the following output:

Error: Cannot find square root of a negative number.
The square root of 25 is 5.0.

Conclusion

In this Python tutorial, we have covered various exercises to enhance our understanding of exception handling. By practicing these exercises, we have learned how to handle different types of exceptions, handle multiple exceptions, use the finally block, and even create custom exceptions. Exception handling is a vital skill for every Python programmer, and these exercises will greatly improve our ability to handle errors effectively.