I just read a short chapter in the book Effective Java, and realized I was doing something pretty dumb in my own code by always creating my own custom exceptions instead of using other exceptions already intended to be reused in the Java API.
- The IllegalArgumentException is supposed to be used when a parameter value is inappropriate.
- The IllegalStateException should be used when your object is not in a proper state when one of its methods is called.
- The NullPointerException can be used when a parameter value is null, but your method doesn't want null values
For my purposes those are the three main exceptions I often seem to create my own classes for. In Effective Java, Joshua Bloch also mentions the
UnsupportedOperationException as other exceptions that developers use (though not as commonly as the first three).
This makes me want to review my old code and see how often I've created my own exceptions when one of these exceptions would have worked just fine.