User Defined Exceptions
User Defined Exceptions
def __str__(self):
return f"{self.message}. Provided age: {self.age}"
Raising User-Defined Exceptions:
Once a custom exception is created, we can raise it in code to signify specific error
conditions. Raising user-defined exceptions involves using the raise statement
Syntax:
raise ExceptionType(args)
Ex:
In this example, the "set_age" function raises an "InvalidAgeError" if the age is outside
the valid range .
def set_age(age):
if age < 18 or age > 100:
raise InvalidAgeError(age)
print(f"Age is set to {age}")
Ex:
try:
set_age(150)
except InvalidAgeError as e:
print(f"Invalid age: {e.age}. {e.message}")
In the above example, the "try" block calls "set_age" with an invalid age. The "except"
block catches the "InvalidAgeError" and prints the custom error message .
EXAMPLE:
class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 18 and 100"):
self.age = age
self.message = message
super().__init__(self.message)
def __str__(self):
return f"{self.message}. Provided age: {self.age}"
def set_age(age):
if age < 18 or age > 100:
raise InvalidAgeError(age)
print(f"Age is set to {age}")
try:
set_age(150)
except InvalidAgeError as e:
print(f"Invalid age: {e.age}. {e.message}")