CH-6 (EXCEPTION HANDLING)
Q.11 Write a program to read the details of student for result preparation. Incorporate all possible exception
handling code such as value error, index error, zero division error, zero defined exceptions, etc.
Solution:
def get_student_details():
try:
name = input("Enter student name: ")
roll_no = int(input("Enter roll number: "))
subjects = int(input("Enter number of subjects: "))
if subjects <= 0:
raise ZeroDivisionError("Number of subjects must be greater than zero.")
marks = []
for i in range(subjects):
mark = int(input(f"Enter marks for subject {i+1}: "))
if mark < 0 or mark > 100:
raise ValueError("Marks should be between 0 and 100.")
marks.append(mark)
try:
print("Trying to access 10th subject (to show IndexError):", marks[9])
except IndexError:
print("Index Error: Trying to access a subject that doesn't exist.")
total = sum(marks)
average = total / subjects
print("\n--- Result Summary ---")
print("Name:", name)
print("Roll No:", roll_no)
print("Marks:", marks)
print("Total:", total)
print("Average:", round(average, 2))
except ValueError as ve:
print("Value Error:", ve)
except ZeroDivisionError as zde:
print("Zero Division Error:", zde)
except Exception as e:
print("Unexpected Error:", e)
finally:
print("\nProcess completed.")
get_student_details()
Q.10 Write a function to read a time-class object storing hours and minutes. Raise a user-defined error if values other
than 0….23 is entered for hours and other than 0…..59 is entered for minutes.
Solution:
class InvalidTimeError(Exception):
def _init_(self):
self.message = message
super()._init_(self.message)
def read_time():
try:
hours = int(input("Enter hours (0–23): "))
minutes = int(input("Enter minutes (0–59): "))
if not (0 <= hours <= 23):
raise InvalidTimeError("Hours must be between 0 and 23.")
if not (0 <= minutes <= 59):
raise InvalidTimeError("Minutes must be between 0 and 59.")
print(f"Time entered: {hours:02d}:{minutes:02d}")
except ValueError:
print("Value Error: Please enter numeric values only.")
except InvalidTimeError as e:
print("Time Error:", e)
finally:
print("Time reading process completed.")
# Call the function
read_time()
Q.9
a)
try:
fs = open("/notthere")
exception IOError: # except FileNotFoundError
print("The file does not exist, exiting gracefully")
print("This line will always print")
b)
try:
fh = ------
try:
fh1= -----
except FileNotFoundError:
print(----)
except FileNotFoundError:
print( ---)
C)
def ret():
sqrs = [x**2 for x in range(1, 10)]
i=0
while True:
yield sqrs[i]
i += 1
c = ret()
for i in range(9):
print(next(c))
Q.8
Ans. Output 3
-2
-0.5 -1
-1.0 0
division by zero
1
1.0 2
0.5
Q.7
A) Checks if the filename string is empty
Also, if filename is given but file doesn’t exist then it’ll raise FileNotFoundError and crash, it’ll not print the
message.
B)This will catch the exception and print the message.
Q.6
(e.message ---- > e )
True
Exception: f: argument must be greater than zero