Table of Contents

Mastering Python Exception Recovery with the Finally Clause

Example Description
Enhance your Python programming skills by mastering the art of exception recovery using the finally clause. Join us in exploring a practical example that combines exception handling with code cleanup, ensuring your code remains robust and reliable.

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:

  1. Display “Practicing for try block” to set the context for the code.
  2. The try block encapsulates code that may raise exceptions during execution.
  3. Initialize numerator to 50.
  4. Prompt the user to input the denominator using the input function.
  5. Convert the input to an integer and store it in denom.
  6. If a valid non-zero integer is entered, calculate the quotient (numerator/denom).
  7. Print “Division performed successfully” to signify a successful division.
  8. If the user enters 0 as the denominator, a ZeroDivisionError occurs during the division operation.
  9. 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.
  10. If no exceptions arise (i.e., the try block executes without errors), the else block is executed.
  11. 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