1

I'm working on making a codebase complaint with a list of PMD rules. These include that you're not allowed to throw or catch NullPointerExceptions. I found this method which requires 2 instance variables to be non-null in order to run. It throws a NullPointerException otherwise:

public String build() {
if (apiKey == null || url == null) {
    throw new NullPointerException(
            "Cannot build: API key and URL must be set");
}

What should it be throwing instead? it seems to me that NullPointerException would be the bast call. The only other thing that comes to mind is IllegalArgumentException, but these aren't really arguments, so I don't think it really fits.

2 Answers 2

7

IllegalStateException seems entirely appropriate here:

Signals that a method has been invoked at an illegal or inappropriate time.

That describes the situation reasonably clearly, doesn't it?

Sign up to request clarification or add additional context in comments.

Comments

6

IllegalStateException springs to mind.

One thing to consider here is whether this should be a checked or an unchecked exception. You could also consider making your own explicit Exception for this case if it can usefully be handled differently from the generic IllegalStateException.

2 Comments

+1 Although Jon Skeet beat you by 10 seconds. I'll be good to you.
@PaulVargas Yeah, but it's Jon Skeet. Even Chuck Norris can't get an answer in before Jon Skeet: meta.stackexchange.com/questions/9134/jon-skeet-facts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.