Junior — Middle
How is error handling with exceptions implemented in Python and how to use them correctly?
sobes.tech AI
Answer from AI
Error handling in Python is done using the try-except construct. The try block contains code that may raise an exception, and the except block contains code to handle that exception.
Proper use of exceptions includes:
- Catching only those exceptions that you expect and can handle.
- Not using an empty except without specifying the exception type, to avoid hiding errors.
- Using finally for code that must run in any case (for example, closing files).
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not possible")
finally:
print("Operation completed")
This approach helps make the program more robust and controllable when errors occur.