Table of Contents

Python Try and Except

Example Description
Learn how to implement try and except blocks in Python to gracefully handle division errors. This tutorial guides you through a practical example where we calculate the quotient of two numbers while safeguarding against zero denominators.

Introduction:

In Python, the try and except blocks provide a way to handle exceptions and errors gracefully. They allow you to protect your code from crashing when an unexpected situation arises. In this tutorial, we will explore the use of try and except blocks through a program that calculates the quotient of two numbers. We will ensure that the denominator is not zero and handle the ZeroDivisionError gracefully. By the end of this guide, you’ll have a solid understanding of how to use try and except to make your Python programs more robust.

Code:

print("Practicing for try block")
try:
 numerator=50
 denom=int(input("Enter the denominator"))
 quotient=(numerator/denom)
 print(quotient)
 print("Division performed successfully")
except ZeroDivisionError:
 print("Denominator as ZERO.... not allowed")
print("OUTSIDE try..except block")

Logic:

  1. The line practicing for try block is printed, which is just an initial message.
  2. The try block is introduced, and the code within this block is attempted to be executed. The user is prompted to input the value of the denominator. if the user provides a valid integer value for the denominator, the program calculates the quotient (numerator/denom).
  3. If the value of denom is not zero, the quotient is printed along with the message Division Performed Successfully.
  4. if the user inputs 0 as the value of denom, the division by zero occurs, resulting in a ZeroDivisionError.
  5. Then denominator as zero not allowed printed.

Output:

>>Practicing for try block

>>Enter the denominator: 0

>>Denominator as ZERO…. not allowed

>>OUTSIDE try..except block