Table of Contents

Python Exception Handling with Finally Clause

Example Description
Discover the resilience of Python's finally clause in this detailed guide. Learn how to handle exceptions while ensuring critical cleanup tasks. Explore a practical example that demonstrates the power of the finally clause in enhancing your Python programming skills.

Introduction:

Effective exception handling is vital for reliable Python code. In this guide, we delve into the finally clause, a potent construct for ensuring code cleanup regardless of exceptions. You’ll see how to manage division errors, including division by zero and non-integer inputs, all while executing essential tasks with the finally clause.

Code:

print("Handling exception using try...except...else...finally")
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")
except ValueError:
  print("Only INTEGERS should be entered")
else:
  print("The result of division operation is ", quotient)
finally:
  print("OVER AND OUT")

Logic:

  1. Display “Handling exception using try…except…else…finally” to clarify the code’s intent.
  2. The try block contains code that may trigger exceptions during execution.
  3. Set numerator to 50.
  4. Prompt the user to enter the denominator using input.
  5. Convert the input to an integer and store it in denom.
  6. If a valid non-zero integer is given, 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 prohibited.
  10. If the user inputs a non-integer value (e.g., a string) for the denominator, a ValueError occurs during conversion.Display “Only INTEGERS should be entered” to convey that only integer values are accepted.
  11. If no exceptions arise (i.e., the try block executes without errors), the else block is executed. Inside the else block, print “The result of the division operation is” along with the calculated quotient, showcasing the successful division.
  12. The finally block is executed regardless of whether exceptions occurred. Inside the finally block, print “OVER AND OUT” to signal the completion of essential cleanup tasks.

Output:

>>Handling exception using try…except…elsefinally

>>Enter the denominator: 5

>>Division performed successfully

>>The result of the division operation is 10.0

>>OVER AND OUT