Bird
0
0

You want to create a custom exception InvalidAgeError that triggers when age is below 0 or above 120. Which approach best uses custom exceptions to handle this validation?

hard📝 Application Q15 of 15
Python - Custom Exceptions
You want to create a custom exception InvalidAgeError that triggers when age is below 0 or above 120. Which approach best uses custom exceptions to handle this validation?
APrint error message instead of raising exceptions
BUse only built-in ValueError without custom exceptions
CDefine <code>InvalidAgeError</code> inheriting Exception, raise it in a function checking age limits
DCatch all exceptions with a generic except block without custom exceptions
Step-by-Step Solution
Solution:
  1. Step 1: Understand validation needs

    Age must be checked for invalid values and a clear error raised if invalid.
  2. Step 2: Use custom exception for clarity

    Defining InvalidAgeError inheriting from Exception and raising it on invalid age clearly signals this specific error.
  3. Step 3: Compare other options

    Using only built-in exceptions or printing errors reduces clarity and control. Catching all exceptions generically hides specific issues.
  4. Final Answer:

    Define InvalidAgeError inheriting Exception, raise it in a function checking age limits -> Option C
  5. Quick Check:

    Custom exception for specific validation error [OK]
Quick Trick: Raise custom exceptions for clear, specific validation errors [OK]
Common Mistakes:
  • Relying only on built-in exceptions
  • Printing errors instead of raising
  • Using generic except blocks hiding issues

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes