Computer Science
How can you handle an exception in Python? Write sample code to illustrate it.
Python Exception Handling
1 Like
Answer
In Python, we can handle exceptions using the try-except block. It includes the following steps:
- Firstly, the moment an error occurs the state of execution of the program is saved.
- Normal flow of the program is interrupted.
- A special function or piece of code known as exception handler is executed.
- Execution of the program is resumed with the previously saved data.
Here's an example of how to handle an exception:
def divide_numbers(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print("Division result:", result)
finally:
print("End of division operation.")
divide_numbers(10, 2)
divide_numbers(10, 0)
Output
Division result: 5.0
End of division operation.
Error: Division by zero is not allowed.
End of division operation.
This Python code defines a function divide_numbers
that performs division between two numbers x
and y
. It uses a try-except block to handle exceptions that may arise during division, specifically the ZeroDivisionError. If a division by zero occurs, the program prints an error message indicating that division by zero is not allowed. Otherwise, if the division operation succeeds without any exceptions, it prints the result of the division. The finally block is executed in both cases, indicating the end of the division operation.
Answered By
3 Likes