Java: Appropriate exception for initialization error

If you are throwing an exception in a Factory due to insufficient data, I like to throw an IllegalStateException with a description similar to “cannot construct X, no Y has been set”.

If you are throwing an exception in a Factory due to conflicting data, I like to throw an
IllegalStateException with a description similar to “cannot construct X, Y conflicts with Z”.

If you are throwing an exception in a Factory due to a bad (or nonsensical) value, I like to throw an IllegalArgumentException with a description similar to “Y cannot be A”.

If you are throwing an exception in a Factory due to a missing value, I like to throw an IllegalArgumentException with a description similar to “Y cannot be null”.

The last preference is up to some debate. Some people suggest that it might be better to throw a NullPointerException; in my case, we avoid them at all costs since many customers tend to not read the exception message (and assume that NullPointerException means a coding error).

In any event, you should provide a good, specific, message as to why the exception was thrown, to ease your future support costs of seeing that exception raised a few months from now.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)