0% found this document useful (0 votes)
10 views6 pages

Python Custom Exceptions and Error Handling

Practical assignment
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Python Custom Exceptions and Error Handling

Practical assignment
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Practical No 8

SET A
1) Define a custom exception class which takes a string message as
attribute.
Code:
class CustomError(Exception):
def __init__(self, message):
[Link] = message
super().__init__([Link])

try:
raise CustomError("This is a custom exception.")
except CustomError as e:
print(f"Caught an exception: {[Link]}")

Output:
Caught an exception: This is a custom exception.

2) Write a function called oops that explicitly raises a IndexError


exception when called. Then write another function that calls oops
inside a try/except statement to catch the error.
Code:
def oops():
raise IndexError

def catch_oops():
try:
oops()
except IndexError:
print("Caught the error from oops function!")
catch_oops()

Output:
Caught the error from oops function!

SET B
1) Define a class Date(Day, Month, Year) with functions to accept and
display it. Accept date from user. Throw user defined exception
“invalidDateException” if the date is invalid.
Code:
class InvalidDateException(Exception):
pass

class Date:
def __init__(self, day=1, month=1, year=2000):
[Link] = day
[Link] = month
[Link] = year

def accept_date(self):
try:
d, m, y = map(int, input("Enter date (DD/MM/YYYY): ").split('/'))
if not (1 <= m <= 12 and 1 <= d <= 31 and y > 0):
raise InvalidDateException("Date values are out of range.")
[Link] = d
[Link] = m
[Link] = y
except ValueError:
raise InvalidDateException("Invalid format for date.")

def display_date(self):
print(f"Date: {[Link]:02d}/{[Link]:02d}/{[Link]}")

try:
my_date = Date()
my_date.accept_date()
print("\nDate accepted successfully.")
my_date.display_date()
except InvalidDateException as e:
print(f"\nError: {e}")

Output (Example with invalid input):


Enter date (DD/MM/YYYY): 35/14/2023

Error: Date values are out of range.

2) Write text file named [Link] that contains integers, characters and
float numbers. Write a Python program to read the [Link] file. And
print appropriate message using exception.
Code:
with open("[Link]", "w") as f:
[Link]("101\n")
[Link]("Python\n")
[Link]("99.9\n")
[Link]("-25\n")
[Link]("c\n")

print("Reading from [Link] and identifying data types:\n")


with open("[Link]", "r") as f:
for line in f:
item = [Link]()
try:
val = int(item)
print(f'Read "{item}" -> This is an Integer.')
continue
except ValueError:
pass

try:
val = float(item)
print(f'Read "{item}" -> This is a Float.')
except ValueError:
print(f'Read "{item}" -> This is a Character or String.')

Output:
Reading from [Link] and identifying data types:

Read "101" -> This is an Integer.


Read "Python" -> This is a Character or String.
Read "99.9" -> This is a Float.
Read "-25" -> This is an Integer.
Read "c" -> This is a Character or String.

SET C
1) Write a function called safe... Put safe in a module file called
[Link], and pass it the oops function interactively... expand safe to
also print a Python stack trace...
Note: This solution requires two separate files in the same directory. First, create [Link] and then
create [Link] to run the test.
File 1: [Link]
import sys
import traceback
def safe(func, *args):
try:
func(*args)
except:
print("--- An Exception Occurred ---")
exc_type, exc_value, _ = sys.exc_info()
print(f"Exception Type: {exc_type}")
print(f"Exception Value: {exc_value}")
print("\n--- Python Stack Trace ---")
traceback.print_exc(file=[Link])
print("--------------------------")

File 2: [Link]
from tools import safe

def oops():
x = [1, 2, 3]
print(x[100])

def divide(x, y):


result = x / y
print(result)

print("Running safe() with the 'oops' function...")


safe(oops)

print("\nRunning safe() with a ZeroDivisionError...")


safe(divide, 10, 0)

Output (from running [Link]):


Running safe() with the 'oops' function...
--- An Exception Occurred ---
Exception Type: <class 'IndexError'>
Exception Value: list index out of range

--- Python Stack Trace ---


Traceback (most recent call last):
File "[Link]", line 6, in safe
func(*args)
File "[Link]", line 6, in oops
print(x[100])
IndexError: list index out of range
--------------------------

Running safe() with a ZeroDivisionError...


--- An Exception Occurred ---
Exception Type: <class 'ZeroDivisionError'>
Exception Value: division by zero

--- Python Stack Trace ---


Traceback (most recent call last):
File "[Link]", line 6, in safe
func(*args)
File "[Link]", line 9, in divide
result = x / y
ZeroDivisionError: division by zero

You might also like