Пропустить до содержимого

Решение упражнений по обработке исключений в Python

[

Python Exception Handling Exercises

Exercise 1: Handling ZeroDivisionError

When working with mathematical calculations in Python, it is important to be aware of potential errors that may occur, such as the ZeroDivisionError. This error occurs when attempting to divide a number by zero. To handle this error, you can use the try-except block.

try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero")

In the above example, the try block attempts to perform the division operation. If a ZeroDivisionError occurs, the code within the except block will be executed, printing an error message.

Exercise 2: Handling FileNotFoundError

When working with files in Python, it is common to encounter the FileNotFoundError if the specified file does not exist. To handle this error, you can use the following code:

try:
file = open("nonexistent_file.txt", "r")
except FileNotFoundError:
print("Error: File not found")

In the above example, the try block attempts to open a file that does not exist. If the FileNotFoundError occurs, the code within the except block will be executed, printing an error message.

Exercise 3: Handling ValueError

The ValueError is another common exception in Python that occurs when an operation or function receives an argument of the correct type but an inappropriate value. To handle this error, you can use the following code:

try:
number = int("abc")
except ValueError:
print("Error: Invalid value")

In the above example, the try block attempts to convert the string “abc” to an integer. Since this is not a valid integer, a ValueError occurs and the code within the except block is executed, printing an error message.

Exercise 4: Raising Custom Exceptions

In Python, you can also define and raise your own custom exceptions to handle specific situations. To raise a custom exception, you can use the raise keyword.

def sqrt(n):
if n < 0:
raise ValueError("Cannot calculate square root of negative number")
else:
return n ** 0.5
try:
result = sqrt(-4)
except ValueError as e:
print(e)

In the above example, the sqrt function calculates the square root of a number. If a negative number is passed as an argument, a custom ValueError is raised with a specific error message. The code within the except block handles the raised exception and prints the error message.

By utilizing exception handling techniques, you can handle errors gracefully in your Python programs and improve the overall robustness of your code.

For more detailed exercises and examples on Python exception handling, refer to the official Python documentation or online Python learning platforms such as DataCamp.