Sobes.tech
Junior — Middle

How can you handle exceptions in Python programs?

sobes.tech AI

Answer from AI

In Python, the try-except construct is used to handle exceptional situations. The try block contains code that might raise an exception, and the except block contains code that handles this exception. You can also use else blocks (executed if no exceptions occur) and finally blocks (executed always, regardless of exceptions).

Example:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero is not possible")
else:
    print("Calculation result:", result)
finally:
    print("Finally block executed")

This approach helps avoid abrupt program termination and allows for proper error response.