Table of Contents

Python Exception Handling with Try-Except-Else

Example Description
Master the art of Python exception handling using the try-except-else construct. Learn how to gracefully manage division errors while leveraging the power of the else clause.

Introduction:

Exception handling is a crucial skill in Python programming, ensuring smooth execution and robustness. In this tutorial, we will explore the use of try-except-else to manage division errors effectively. By incorporating the else clause, you can execute code blocks that depend on successful try blocks. Follow along with the provided example to gain a deeper understanding of handling exceptions in Python.

Code:

print("Handling exception using try...except...else")
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)

Logic:

  1. Display the message “Handling exception using try…except…else” to indicate the purpose of this code section.
  2. The try block is introduced to encapsulate the code that may raise exceptions during execution.
  3. the variable numerator The program prompts the user to input the value of the denominator using the input function. The input is converted to an integer using int() , and the result is stored in the variable denom .is assigned the value 50
  4. If the user enters a valid integer value for the denominator, the program proceeds to calculate the quotient (numerator/denom).The message “Division performed successfully” is printed, indicating the successful execution of the try block.
  5. if the user enters 0 as the denominator, resulting in a ZeroDivisionError during the division operation.
  6. The except ZeroDivisionError block catches this exception and gracefully.

Output:

    >>Handling exception using try…except…else

>>Enter the denominator: 5

>>Division performed successfully

>>The result of the division operation is 10.0