Introduction:
Exception handling is a vital aspect of writing reliable Python code. In this guide, we delve into the powerful finally clause, which allows you to recover from exceptions while ensuring essential code cleanup. Through a practical example, you’ll learn how to handle division errors gracefully and execute necessary post-exception tasks.
Code:
print("Practicing for try block")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
else:
print("The result of division operation is ", quotient)
finally:
print("OVER AND OUT")
Logic:
- Display “Practicing for try block” to set the context for the code.
- The try block encapsulates code that may raise exceptions during execution.
- Initialize numerator to 50.
- Prompt the user to input the denominator using the input function.
- Convert the input to an integer and store it in denom.
- If a valid non-zero integer is entered, calculate the quotient (numerator/denom).
- Print “Division performed successfully” to signify a successful division.
- If the user enters 0 as the denominator, a ZeroDivisionError occurs during the division operation.
- The except ZeroDivisionError block gracefully handles this specific exception. Display “Denominator as ZERO is not allowed” to inform the user that division by zero is not permitted.
- If no exceptions arise (i.e., the try block executes without errors), the else block is executed.
- The finally block is executed regardless of whether exceptions occurred.
Output:
>>Practicing for try block Enter the denominator: 5
>>Division performed successfully
>>The result of division operation is 10.0
>>OVER AND OUT