Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right exception to throw for the lack of a system property

Tags:

java

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?

like image 1000
Anthony Accioly Avatar asked Jul 08 '14 14:07

Anthony Accioly


2 Answers

I only add to Vash's answer for the Spring Framework. If your using the Spring Framework and you want to be consistent with how most of the components in Spring do it then I would say you should use IllegalStateException (or your own derivation).

In Spring most components that do a @PostConstruct or @Override void afterPropertiesSet() throw IllegalStateException using the util org.springframework.util.Assert.state(..).

You can see this done in Spring AMQP as one example.

That being said I have actually filed bugs against Spring MVC where they used IllegalArgumentException instead of a custom and more explicit derived class. With static inline classes its very easy to create a custom exception with out creating another Java file.

like image 26
Adam Gent Avatar answered Nov 15 '22 17:11

Adam Gent


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.

like image 169
Damian Leszczyński - Vash Avatar answered Nov 15 '22 17:11

Damian Leszczyński - Vash