1

I have service, a simple class that need to take input and run some business logic. Before executing this service, the user must set all the data. In general, it look like this:

public class TestService extends InnerServiceBase {

    /**
     * Mandatory input 
     */
    private  Object inputObj;

    @Override
    protected ErrorCode executeImpl() {
        //Some business logic on inputObj
        return null;
    }

    public void setInputObj(Object inputObj) {
        this.inputObj = inputObj;
    }
} 

What is the best runtime exception to throw in case the inputObj is null ?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Moshe Tsabari
  • 362
  • 3
  • 17

3 Answers3

2

IllegalStateException seems like the best fit. The object is not in the correct state to have executeImpl() called on it. Whatever exception you use, make sure the error message is helpful.

Whether you should be using an unchecked exception at all is a whole other question...

Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82
1

Depends on the scenario.

  • If this is part of an API that another developer is using, throwing NullPointerException is reasonable since you don't want that input to be null. Adding a descriptive exception message would be helpful.
  • If you're not interested in throwing an NPE, or this is part of code that's not going into an API, then you could throw an IllegalArgumentException, as null could be considered an illegal argument.
Makoto
  • 104,088
  • 27
  • 192
  • 230
1

If setInputObj is called with a null argument, and that's not valid, then throw NullPointerException. There's some debate over the "correct" exception here (IllegalArgumentException or NullPointerException for a null parameter?), but Guava, Apache Commons Lang and even the JDK itself (Objects.requireNonNull) have settled on NPE.

If executeImpl is called before inputObj has been set, throw IllegalStateException.

Community
  • 1
  • 1
Joe
  • 29,416
  • 12
  • 68
  • 88