Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Table of Contents

...

Checked or Unchecked

From Effective Java:

[A checked exception] puts a nontrivial burden on the programmer. The burden is justified if the exceptional condition cannot be prevented by proper use of the API and the programmer using the API can take some useful action once confronted with the exception. Unless both of these conditions hold, an unchecked exception is more appropriate.

Javadocs

Every checked exception should be documented in the javadoc for the method using the @throws clause.

...

This is thrown when the method cannot be completed because the caller passed in an invalid argument. The method javadoc should make it clear what values are allowedIllegalArgumentException is used for cases that the argument passed to a method is bad in a way that it can never be good (e.g. passing a negative number to a method that requires positive). 

IllegalStateException

This is thrown when the method cannot be completed because the state of the class is incorrect, even if there is no way to change the state. Changing the method arguments would never make the method complete successfully without a state change. 

...

xyz is not a supported type

Avoid throws Exception

If a method throws several types of checked exceptions, never consolidate them into a single 'throws Exception' declaration in an attempt to "simplify" the code. This makes it impossible for the caller to handle the individual exceptions correctly. If a method throws too many types of exceptions, this indicates that the method should perhaps be broken up into multiple methods, or some of those checked exceptions should be unchecked exceptions.


Do not declare that a method throws Exception in any class that is not meant to be implemented by user code. Throwing Exception means your callers are unable to handle your exception without catching other unrelated exceptions at the same time. It also makes it almost impossible to correctly determine if the exception should propagated or logged or retried or ignored.

...