Junior — Middle
Explain the exception handling mechanism using try and except blocks in programming.
sobes.tech AI
Answer from AI
In Python, try and except blocks are used for exception handling — errors that occur during program execution. Code that might cause an error is placed inside the try block. If an exception occurs, execution jumps to the except block, where the error can be handled, such as printing a message or performing alternative actions.
Example:
try:
result = 10 / 0 # Division by zero will raise ZeroDivisionError
except ZeroDivisionError:
print("Error: division by zero is not allowed.")
This mechanism allows the program to handle errors gracefully without crashing.