Site icon DataFlair

Python Program on Exception Handling

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Exception handling is a crucial aspect of Python programming, providing a mechanism to gracefully manage and respond to unforeseen errors or exceptional situations that may occur during code execution. In Python, exceptions are raised when an error occurs, and implementing effective exception handling allows developers to control the flow of their programs, handle errors gracefully, and ensure the stability of the application.

This article delves into the realm of exception handling in Python, exploring its syntax, strategies, and the importance of robust error management in creating reliable and resilient code.

Topic Explanation:

Exception handling enables developers to create robust applications that gracefully handle errors, preventing unexpected crashes and enhancing user experience. By strategically placing try and except blocks, developers can identify potential issues, such as file not found errors or division by zero, and implement tailored responses to address them. Additionally, the else block can be utilized to execute code when no exceptions occur within the try block, providing a streamlined approach to error management.

Exception handling in Python extends beyond built-in exceptions, allowing developers to define and handle custom exceptions, tailoring error responses to specific application requirements. Mastery of exception handling empowers Python developers to create resilient code that can withstand unforeseen circumstances, contributing to the overall reliability and quality of software applications.

Prerequisite:

Code 1 with Comments:

# Exception Handling in Python
try:
    a = int(input("Enter First Number"))  # User input for the first number
    b = int(input("Enter First Number"))  # User input for the second number
    c = a // b  # Division operation
    print("Division is ", c)  # Print the result of the division
except ZeroDivisionError as obj:
    print("Can not divide by zero")  # Handle the ZeroDivisionError exception
except ValueError as obj:
    print("Enter numbers only")  # Handle the ValueError exception

print("This is End Program")  # Print after the try-except block
print("Visit Again")  # Another print statement after the try-except block

Output of code 1:
Enter First Number10
Enter First Number2
Division is 5
This is End Program
Visit Again

Code 1 Explanation:

Code 2 with comments:

# Define a list containing a mix of integers, strings, and floats
mylist = [10, 50, 20, 40, "Data Flair", 60.66, 50, 10, 50]

# Try block to handle potential exceptions
try:
    # Prompt the user to enter an index number
    i = int(input("Enter Index number: "))
    
    # Prompt the user to enter a number
    b = int(input("Enter a number"))
    
    # Attempt to perform integer division and print the result
    print(mylist[i] // b)

# Exception handling for ValueError (invalid integer input)
except ValueError:
    print("Enter a number only")

# Exception handling for other potential exceptions
except Exception:
    print("Error in Program.....")

Output for code2:

Since the code involves user input, the output can vary based on the provided inputs. Here are a few scenarios:

Enter Index number: 3
Enter a number: 5
8

Enter Index number: 10
Enter a number: 2
Error in Program…..

Code 2 Explanation:

Conclusion:

In summary, Python’s adaptability in handling both built-in and custom exceptions offers a potent toolkit for tailoring error responses to the unique needs of diverse applications. Proficiency in the intricacies of exception handling not only shields code from unforeseen circumstances but also contributes to the development of robust and high-quality software solutions. Exception handling remains a critical facet of Python programming, providing a mechanism to gracefully manage and respond to unforeseen errors or exceptional situations during code execution.

Exit mobile version