Professional Documents
Culture Documents
Assignment 5
Assignment 5
[1]: #1
# ZeroDivisionError
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Error:", e)
# NameError
try:
result = x + 5
except NameError as e:
print("Error:", e)
# TypeError
try:
result = "hello" + 5
except TypeError as e:
print("Error:", e)
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code to handle the exception
print("Cannot divide by zero")
1
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
else:
# Code to execute if no exception occurred
print("Division successful")
Division successful
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
# Code that always runs, whether an exception occurred or not
print("Process complete")
Process complete
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful")
finally:
print("Process complete")
Division successful
Process complete
try:
x = -1
if x < 0:
raise ValueError("Number cannot be negative")
except ValueError as e:
print("Error:", e)
2
[7]: #2 -assert
try:
x = 10
assert x < 5, "x should be less than 5"
except AssertionError as e:
print("Assertion Error:", e)
[8]: #2 -finally
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Process complete")
Process complete
[9]: #3
class AgeNotWithinRangeException(Exception):
"""Custom exception for age not within the specified range."""
pass
class NameNotValidException(Exception):
"""Custom exception for invalid name."""
pass
class Student:
def __init__(self, roll_no, name, age, course):
self.roll_no = roll_no
self.name = name
self.age = age
self.course = course
if not self.is_valid_name(name):
raise NameNotValidException("Name should not contain numbers or␣
↪special symbols")
3
return name.isalpha() or ' ' in name
# Example usage
try:
student1 = Student(1, "John Doe", 20, "Mathematics")
print("Student created successfully")
except AgeNotWithinRangeException as e:
print("Error creating student:", e)
except NameNotValidException as e:
print("Error creating student:", e)
try:
student2 = Student(2, "Jane@Doe", 18, "Physics")
print("Student created successfully")
except AgeNotWithinRangeException as e:
print("Error creating student:", e)
except NameNotValidException as e:
print("Error creating student:", e)
[ ]: