使用组合的代码中IllegalArgumentException抛出失效求助
Hey there! Let's figure out why your validation isn't throwing the IllegalArgumentException like you expect. When using composition for data validation, the most common issues usually boil down to where you’re placing your validation logic or not actually triggering it during object instantiation. Let’s break this down step by step:
Common Issues & Fixes
Validation logic isn’t being called during object creation
It’s easy to write a validation method but forget to invoke it in your constructor or factory method. For example, if you’ve isolated your validation in a separate component (per composition principles), you need to explicitly call its validation logic before setting the score.Example of what not to do:
class ScoreValidator { public void checkScore(int score) { if (score <= 0 || score >= 300) { throw new IllegalArgumentException("Score must be 1-299"); } } } public class Player { private int score; private ScoreValidator validator; public Player(int score) { this.validator = new ScoreValidator(); this.score = score; // Oops! Forgot to call validator.checkScore(score) } }Incorrect condition in your validation check
Double-check your boolean logic—small mistakes here can stop exceptions from triggering. For example, if you wrotescore > 0 && score < 300as the valid condition, your exception should trigger when the opposite is true:score <= 0 || score >= 300. Mixing up&&and||is a common slip-up.Exceptions are being silently caught
If you’re instantiating the object inside atry-catchblock that swallowsIllegalArgumentExceptionwithout logging or rethrowing, you’ll never see the error. For example:try { Player badPlayer = new Player(-50); } catch (IllegalArgumentException e) { // No logging or handling here—you’ll think no exception was thrown }
Correct Composition-Based Implementation
Here’s how to structure your code to ensure validation triggers reliably:
// Standalone validator component (follows composition: Player uses this instead of inheriting) class ScoreValidator { public void validate(int score) { if (score <= 0 || score >= 300) { throw new IllegalArgumentException( String.format("Invalid score: %d. Must be between 1 and 299.", score) ); } } } // Class that composes the validator public class Player { private int score; private final ScoreValidator scoreValidator; // Inject the validator (composition in action) public Player(int score, ScoreValidator validator) { this.scoreValidator = validator; // Validate BEFORE assigning the score this.scoreValidator.validate(score); this.score = score; } // If using setters, validate there too public void setScore(int score) { scoreValidator.validate(score); this.score = score; } } // Test it out public class Main { public static void main(String[] args) { // Valid case: no exception Player validPlayer = new Player(150, new ScoreValidator()); // Invalid case: should throw IllegalArgumentException Player invalidPlayer1 = new Player(-20, new ScoreValidator()); // Invalid case: should throw IllegalArgumentException Player invalidPlayer2 = new Player(350, new ScoreValidator()); } }
Quick Tips
- If using a testing framework like JUnit, write a test that explicitly expects the
IllegalArgumentException—this confirms your validation is working as intended. - Always validate input before assigning it to instance variables, so invalid values never get stored even if exceptions are delayed.
内容的提问来源于stack exchange,提问作者pinklitmus

