Table of Contents

Python Try-Except: Handling Multiple Exceptions for Division Operations

Example Description
Learn how to effectively handle division errors in Python using multiple except clauses. This tutorial demonstrates the use of try-except blocks to gracefully manage division by zero and non-integer input scenarios.

Introduction:

Exception handling is a crucial skill for writing reliable Python code. In this tutorial, we will explore the use of multiple except clauses within try-except blocks to handle various types of exceptions. Specifically, we’ll focus on division operations and demonstrate how to handle zero denominators and invalid input (non-integer values) gracefully. By the end of this guide, you’ll be equipped to handle multiple exceptions efficiently in your Python programs.

Code:

print("Handling multiple exceptions")
try:
 numerator=50
 denom=int(input("Enter the denominator: "))
 print(numerator/denom)
 print("Division performed successfully")
except ZeroDivisionError:
 print("Denominator as ZERO is not allowed")
except ValueError:
 print("Only INTEGERS should be entered")

Logic:

  1. The program starts by printing a message indicating that we are practicing with the try block.
  2. The program then prints the message “Handling multiple exceptions” to indicate the topic of this code section.
  3. The try block is introduced, encapsulating the code that may raise error during execution.
  4. The variable numerator is assigned the value 50. The program prompts the user to input the value of the denominator using the input function. The input is then converted to an integer using int(), and the result is stored in the variable denom.
  5. If the user enters a valid integer value for the denominator, the program proceeds to calculate the quotient (numerator/denom). The quotient is printed using print(numerator/denom). The message “Division performed successfully” is printed using print(“Division performed successfully”).

Output:

  >> Handling Multiple Exceptions

>>Enter the denominator: 5

>>10.0

>>Division performed successfully

>>Enter the denominator: 0

>>Denominator as ZERO is not allowed

>>Enter the denominator: abc

>>Only INTEGERS should be entered