Create a Custom Exception
Beginner · Write the code · from Python Custom Exceptions: Build Your Own Error Types
From the lesson: Python Custom Exceptions: Build Your Own Error Types
Imagine your car's dashboard had only one warning light that just said "Problem." Not very helpful, right? You'd want to know: is the engine overheating? Is the oil low? Is a door open? The more specific the warning, the faster you can fix the issue.
Read the lessonCreate a custom exception class called NegativeAgeError that inherits from Exception.
Then write a function called set_age(age) that raises NegativeAgeError with the message "Age cannot be negative: X" (where X is the age) if the age is negative. Otherwise, it prints "Age set to X".
Test it with set_age(25) and catch the error from set_age(-5).
# Create your NegativeAgeError class
# Write the set_age function
# Test with 25 and -5
More Custom Exceptions exercises
All Python exercises · 50 practice problems · Error Handling quiz