An Effective Java note on reusing existing Exception classes

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.

Specifically:

  1. The IllegalArgumentException is supposed to be used when a parameter value is inappropriate.
  2. The IllegalStateException should be used when your object is not in a proper state when one of its methods is called.
  3. 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 IndexOutOfBoundsException, ConcurrentModificationException, and 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.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.