Question
What is the purpose of the else block in exception handling?
Solution
β Verified
In Python, the else block in exception handling is used to define code that should run only if no exception was raised in the try block.
Purpose:
- It separates the code that should only run when the try block is successful, making the intent clearer.
- Helps in cleaner exception handling logic by keeping normal execution flow separate from error handling.
Example:--
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Division successful. Result is:", result)
Click here to download practice questions on
Exception Handling in PythonMore Questions on Exception Handling in Python
Question 6
"Every syntax error is an exception but every exception cannot be a syntax error." Justify the statement.
View solution