Right exception to throw for the lack of a system property

java

Solution

There is none. I would throw the `IllegalStateException`, because you are missing the parameter. This mean that configuration validator has failed and your application is in invalid state. In other words you should never be able to call the `init()` at all.

In case the value of parameter would be invalid, then i would throw an `IllegalArgumentException`.

If you are writing a validator, you should decide between using `RuntimeException` or checked one. When using for example javax.naming.ConfigurationException`, or created own one configuration exception. You API will be able to handle such exception and react properly in term of legacy.

Definitions:

IllegalStateException - Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

IllegalArgumentException - Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Problem

Say I have a system property `MY_PROP`: ``` java -DMY_PROP="My value" ``` This property is necessary for my system to work. What is the right exception to throw if this property is not set? ``` @PostConstruct private void init() { myProp = System.getProperty("MY_PROP"); if (myProp == null) { throw new ???? } // ... } ``` Somehow `IllegalArgumentException` does not feel right. Maybe `IllegalStateException`, `MissingResourceException`, `TypeNotPresentException`? What is the standard practice for this scenario?

Original source