Sometimes, we want to manually throw an error using raise.
π‘ Example:
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
try:
set_age(-1)
except ValueError as e:
print("Error:", e)β Raising exceptions is useful when building functions or APIs that must enforce rules.
Error: Age cannot be negativeπ Real-life Analogy:
You walk into a store with no mask β a guard stops you (raises exception) and redirects politely.