Java › Enums
What is the valueOf() method on an enum, and what happens when you pass a name that doesn't match any declared constant?
IntermediateAnswer
The implicitly-generated static valueOf(String name) method looks up and returns the enum constant whose declared identifier exactly matches the given String (case-sensitive), throwing IllegalArgumentException if no constant with that exact name exists -- useful for parsing an enum from external string input (like a configuration value or API parameter), though because it throws rather than returning a sentinel/null, callers must be prepared to catch IllegalArgumentException or validate the input beforehand if invalid values are a realistic possibility.
enum Status { ACTIVE, INACTIVE, PENDING }
Status s = Status.valueOf("ACTIVE"); // works, returns Status.ACTIVE
try {
Status invalid = Status.valueOf("active"); // throws IllegalArgumentException -- case-sensitive!
} catch (IllegalArgumentException e) {
System.out.println("Invalid status value");
}Real-world example An API endpoint parsing a status query parameter into a Status enum via valueOf() wraps the call in a try-catch to return a clean 400 Bad Request error with a helpful message when a client submits an invalid or mistyped status value, rather than letting an unhandled IllegalArgumentException propagate as a generic 500 error.