Python Exception Handling with Examples

Aim: Use the structure of exception handling all general purpose exceptions.

Program:

# exception handling in python for division by zero error    
try:
    numerator = 10
    denominator = 0
    result = numerator/denominator
    print(result)
except:
    print("Error: Denominator cannot be 0.")

Output: Error: Denominator cannot be 0.
# Catching Specific Exceptions in Python

try:
    even_numbers = [2,4,6,8]
    print(even_numbers[5])

except ZeroDivisionError:
    print("Denominator cannot be 0.")
    
except IndexError:
    print("Index Out of Bound.")
# Output: Index Out of Bound
# program to print the reciprocal of even numbers
#python with else clause
try:
    num = int(input("Enter a number: "))
    assert num % 2 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/num
    print(reciprocal)

#python with try and finally
try:
    numerator = 10
    denominator = 0
    result = numerator/denominator
    print(result)
except:
    print("Error: Denominator cannot be 0.")
    
finally:
    print("This is finally block.")

Output:

 Output: Index Out of Bound

Sample Viva Questions and Answers

  1. What is exception handling in Python?
    Exception handling is a mechanism that allows a program to respond to runtime errors or exceptional conditions gracefully without crashing.

  2. What is the purpose of using try and except blocks?
    The try block contains code that may raise an exception, while the except block defines how to handle the exception if it occurs.

  3. What are some common built-in exceptions in Python?
    Common built-in exceptions include ValueErrorTypeErrorIndexErrorKeyErrorZeroDivisionError, and FileNotFoundError.

  4. What is a ValueError?
    ValueError occurs when a function receives an argument of the right type but an inappropriate value, such as trying to convert a non-numeric string to an integer.

  5. What is a TypeError?
    TypeError is raised when an operation or function is applied to an object of an inappropriate type, such as adding a string to an integer.

  6. How can you catch multiple exceptions in a single except block?
    You can catch multiple exceptions by specifying them as a tuple in the except statement, allowing you to handle them with the same code.

  7. What is the purpose of the finally block?
    The finally block is used to define code that should run regardless of whether an exception occurred or not, often used for cleanup actions.

  8. What is the difference between an exception and an error?
    An exception is a specific condition that disrupts the normal flow of a program, while an error generally refers to a more serious issue that may not be recoverable.

  9. How can you raise an exception manually in Python?
    You can raise an exception manually using the raise statement, allowing you to trigger an exception based on specific conditions in your code.

  10. What are some best practices for exception handling?
    Best practices include catching specific exceptions rather than using a generic except, logging exceptions for debugging, and ensuring that cleanup code is placed in a finally block.

📌 Python Programming Lab – Complete Guide

Welcome to the Python Programming Lab! This comprehensive lab series is designed to provide a solid foundation in Python programming through practical exercises and hands-on learning. From basic calculations to advanced concepts like file handling, modules, and GUI programming, this lab covers it all. Let’s dive into what you’ll be learning throughout this lab course.


🔍 Week 1: Introduction to Python Basics

In the first week, you will explore fundamental Python concepts aimed at building a strong foundation for your programming journey.

  • Getting Started with Python: Visit the Python Official Website to explore documentation and use the help() function in the interpreter.
  • Python as a Calculator: Learn how to perform basic arithmetic operations like addition, subtraction, multiplication, and division.
  • Calculating Compound Interest: Write a program to calculate compound interest using the formula with given principal, rate, and time.
  • Distance Calculation: Compute the distance between two points using the distance formula.
  • Reading User Details: Write a program to collect and print user details like name, address, email, and phone number.

🔍 Week 2: Python Loops and Conditional Statements

This week focuses on using loops and conditional statements effectively.

  • Pattern Generation: Print a triangle pattern using nested loops.
  • Character Identification: Write a program to identify whether the input is a digit, lowercase, uppercase, or special character.
  • Fibonacci Sequence Generation: Use a while loop to generate the Fibonacci series.
  • Prime Numbers Identification: Find all prime numbers within a specified range using the break statement.

🔍 Week 3: Data Structures and Functions

Dive into data structures and creating functions to enhance your programming skills.

  • Converting Lists and Tuples to Arrays: Understand how to convert different data structures.
  • Finding Common Values: Compare two arrays to find common values.
  • Calculating GCD: Create a function to calculate the greatest common divisor (GCD) of two numbers.
  • Palindrome Checker: Write a function that checks if a given string is a palindrome.

🔍 Week 4: Advanced Functions and String Manipulation

This week emphasizes sorting, handling duplicate elements, and manipulating strings effectively.

  • Checking Sorted Lists: Write a function to check if a list is sorted.
  • Handling Duplicates: Create functions to detect and remove duplicates from lists.
  • Dictionary Inversion: Write a program to swap keys and values in a dictionary.
  • String Manipulation: Add commas between characters, remove words from strings, and convert sentences to title case without using built-in functions.
  • Binary String Generation: Use recursion to generate all binary strings of a specified length.

🔍 Week 5: Working with Matrices and Modules

Learn to work with matrices and create custom modules for various applications.

  • Matrix Operations: Define, print, add, and multiply square matrices using Python.
  • Creating Modules: Build modules using geometrical shapes and their operations.
  • Exception Handling: Implement exception handling for robust error management.

🔍 Week 6: Object-Oriented Programming and Validation

This week focuses on using classes, inheritance, and validation techniques.

  • Drawing Shapes with Classes:
    • Create classes for rectangles, points, and circles, and draw them on a canvas.
    • Add colors and attributes to these shapes to enhance visualization.
  • Method Resolution Order (MRO): Demonstrate MRO in multiple inheritance scenarios.
  • Data Validation: Write programs to validate phone numbers and email addresses.

🔍 Week 7: File Handling and Text Processing

Master file handling techniques and analyzing text data.

  • File Merging: Combine the contents of two files into a new file.
  • Word Search: Create a function to find specific words in a file.
  • Word Frequency Analysis: Identify the most frequent words in a text file.
  • Text Statistics: Count words, vowels, blank spaces, lowercase, and uppercase letters in a file.

🔍 Week 8: Python Libraries and GUI Programming

Explore advanced Python libraries and build simple graphical user interfaces.

  • NumPy, Plotly, and Scipy: Learn how to install and use these powerful libraries for data analysis and visualization.
  • Digital Logic Gates: Implement logic gate operations such as AND, OR, NOT, and EX-OR.
  • Adder Circuits: Create programs for Half Adders, Full Adders, and Parallel Adders.
  • GUI Programming: Build a simple window wizard with text labels, input fields, and buttons using Python’s GUI tools.

🌟 Conclusion:

The Python Programming Lab R23 provides you with a strong foundation in Python programming through a wide range of exercises, from basic concepts to advanced topics. By the end of this lab, you will have gained valuable skills in data processing, file handling, OOP, modules, and GUI development. Start coding and enhance your Python skills! 🚀


;