Bird
Raised Fist0

You want to create a function that raises a custom error if a username is empty or less than 3 characters. Which code correctly raises a custom error with message 'Invalid username'?

hard🚀 Application Q8 of Q15
Python - Advanced Exception Handling
You want to create a function that raises a custom error if a username is empty or less than 3 characters. Which code correctly raises a custom error with message 'Invalid username'?
Adef check_user(name): if len(name) < 3: print('Invalid username')
Bdef check_user(name): if name == '' or len(name) > 3: raise Exception('Invalid username')
Cdef check_user(name): if not name or len(name) < 3: raise ValueError('Invalid username')
Ddef check_user(name): if name is None: raise 'Invalid username'
Step-by-Step Solution
Solution:
  1. Step 1: Check condition for empty or short username

    def check_user(name): if not name or len(name) < 3: raise ValueError('Invalid username') uses 'not name' to check empty and 'len(name) < 3' correctly.
  2. Step 2: Confirm correct raise syntax and message

    def check_user(name): if not name or len(name) < 3: raise ValueError('Invalid username') raises ValueError with the correct message.
  3. Final Answer:

    def check_user(name): if not name or len(name) < 3: raise ValueError('Invalid username') -> Option C
  4. Quick Check:

    Correct condition and raise syntax used [OK]
Quick Trick: Check empty with 'not' and raise ValueError with message [OK]
Common Mistakes:
MISTAKES
  • Using wrong condition logic
  • Printing error instead of raising
  • Raising string instead of Exception

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes