Решение упражнений по обработке исключений в 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.
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:
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:
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.
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.