← Back to Exceptions
Question 153
Custom Exception Class
Custom Exception Class
Create a custom exception class ValidationError that inherits from std::exception, then use it in a function.
Requirements for ValidationError:
1. Private std::string message field
2. Constructor ValidationError(std::string msg): stores the message
3. Override what() const noexcept to return message.c_str()
Also write a function validateUsername(const std::string& name):
- If name is empty, throw ValidationError("Username cannot be empty")
- If name.length() < 3, throw ValidationError("Username too short")
- Otherwise return name
Do NOT write a main function.
Expected Output:
alice= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
ClassesExceptions
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.