019-003-006
throws: Exception Propagation
Medium
Problem Description
throws: Exception Propagation
In this problem, you will create a program that propagates exceptions from a method to its caller using the throws keyword and implements a file name validation system.
Learning Objective: Learn to propagate exceptions to caller using throws keyword
Overview
throws keyword declares that a method may throw specific exceptions. It delegates exception handling responsibility to the caller.
Specifications
Implement a file name validation system:
FileValidatorclass:static void validateFileName(String fileName) throws IllegalArgumentException- If fileName is null or empty, throw
IllegalArgumentException - Message:
"Invalid file name" - If valid: output
"Valid file name: [fileName]"
- If fileName is null or empty, throw
Mainclass:- Use try-catch to execute:
- Validate
"document.txt"(success) - Validate
""(empty string — throws exception) - catch: output
"Error: [exception message]" - Validate
"report.pdf"(success)
- Validate
- Use try-catch to execute:
How Tests Work
This problem tests the validateFileName method directly, verifying both normal cases (no exception) and error cases (IllegalArgumentException thrown).
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up