Recap - Validated User
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 63 of 87.
Challenge
EasyLet's build a complete user registration system that validates input data and uses custom exceptions to communicate exactly what went wrong! You'll combine everything from this chapter: custom checked and unchecked exceptions, the exception hierarchy, and try-with-resources with an auto-closeable validator.
You'll organize your code across five files:
ValidationException.java: Create a checked exception that serves as the base for all validation errors. This exception should extendExceptionand include a constructor that accepts a message.InvalidUsernameException.java: Create a checked exception for username validation failures. This should extend yourValidationExceptionclass, creating a small exception hierarchy. Include a constructor that accepts a message and passes it to the parent.InvalidAgeException.java: Create an unchecked exception for age-related errors (like negative ages, which represent programming errors). This should extendRuntimeExceptionwith a constructor that accepts a message.UserValidator.java: Create a class that implementsAutoCloseableto simulate a validation session that should be properly closed. Your validator should:Print
Validator session startedin the constructor.Have a
validateUsername(String username)method that throwsInvalidUsernameExceptionif the username is null, empty, or less than 3 characters (with message"Username must be at least 3 characters"). Otherwise, printUsername '[username]' is valid.Have a
validateAge(int age)method that throwsInvalidAgeExceptionif age is negative (with message"Age cannot be negative: [age]"). If age is less than 13, throwValidationExceptionwith message"Must be at least 13 years old". Otherwise, printAge [age] is valid.Implement
close()to printValidator session closed.Main.java: Bring your validation system together! You'll receive two inputs: a username (String) and an age (integer).Use try-with-resources to create a
UserValidator. Inside the try block, first validate the username, then validate the age. If both pass, printUser registration successful!Catch
InvalidUsernameExceptionand printUsername error: [message]. CatchInvalidAgeExceptionand printAge error: [message]. CatchValidationException(the parent) and printValidation error: [message].The validator should automatically close regardless of whether validation succeeds or fails!
You will receive two inputs in order: username (String) and age (integer).
This challenge brings together the entire chapter: you'll build an exception hierarchy with ValidationException as a parent, use both checked and unchecked exceptions appropriately, and ensure your validator resource is always cleaned up with try-with-resources. Notice how catching the parent ValidationException after its child InvalidUsernameException lets you handle specific cases first while still catching other validation errors!
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
String username = scanner.nextLine();
int age = scanner.nextInt();
// TODO: Use try-with-resources to create a UserValidator
// Inside the try block:
// 1. Validate the username
// 2. Validate the age
// 3. If both pass, print "User registration successful!"
// TODO: Catch InvalidUsernameException and print "Username error: [message]"
// TODO: Catch InvalidAgeException and print "Age error: [message]"
// TODO: Catch ValidationException (parent) and print "Validation error: [message]"
// Note: The validator should automatically close regardless of success or failure!
}
}
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting10Exception Handling in OOP
Exception Class HierarchyCustom ExceptionsChecked vs Unchecked ErrorsTry With Resources PatternRecap - Validated User2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System