Lab 5
Lab 5
Objective
- To understand how to detect and handle runtime errors using exception handling techniques in
Python, including built-in exceptions and custom-defined exceptions.
Theory
Errors in programming are common and can cause a program to stop unexpectedly. Python provides a
way to handle errors gracefully using try-except blocks, so the program doesn't crash.
Code Implementations:
1. Handle division by zero exception.
- try:
- a = int(input("Enter numerator: "))
- b = int(input("Enter denominator: "))
- result = a / b
- print("Result:", result)
- except ZeroDivisionError:
- print("Error: Cannot divide by zero.")
2. Handle multiple exceptions (File Not Found, Index Out of Range, etc.).
- try:
- file = open("data.txt", "r")
- content = file.read()
- print(content)
- numbers = [1, 2, 3]
- print(numbers[5])
-
- except FileNotFoundError:
- print("Error: File not found.")
- except IndexError:
- print("Error: Index is out of range.")
- except Exception as e:
- print("An unexpected error occurred:", e)
- class NegativeNumberError(Exception):
- pass
-
- def check_positive(num):
- if num < 0:
- raise NegativeNumberError("Negative numbers are not allowed.")
- else:
- print("You entered:", num)
-
- try:
- n = int(input("Enter a positive number: "))
- check_positive(n)
- except NegativeNumberError as e:
- print("Custom Error:", e)
Conclusion
In this lab, we learned how to use Python’s error-handling features to catch and manage exceptions like
division by zero, file not found, and index out of range. We also created a custom exception class,
which helps in handling specific errors more meaningfully. Error handling is essential for building safe
and robust applications.