Christopher Barber
Christopher Barber

Reputation: 2678

Best way to allow NullPointerException when null analysis is turned on

In Java JDT plugin for Eclipse, there is an option to turn on errors and warnings for null pointer issues. You can annotate your code to indicate whether a field, variable, parameter, or return value can be null or not.

The problem is this. If you enable this feature and enable Errors for Null pointer access and mark a field as possibly null

   private @Nullable SomeClass _delegate;

but you actually WANT particular accesses of this field to generate a NullPointerException if null:

   /**
    * @throws NullPointerException if delegate is null
    */
   void someMethod()
   {
       _delegate.someMethod();
   }

As written, I can't do this because the JDT gives me a "potential null pointer" error. The JDT does not provide any way to suppress errors (as far as I know).

I can lower the severity of this error to warning and then suppress it, or I could explicitly check for null and manually throw a NullPointerException. Is there some other good way around this problem?

Upvotes: 0

Views: 215

Answers (2)

Christopher Barber
Christopher Barber

Reputation: 2678

One possible solution is to use the Objects.requireNonNull method that was introduced in Java 7. This will do an explicit null check, so I could write:

Objects.requireNonNull(_delegate).someMethod();

I am not sure whether or not the JVM is smart enough to optimize this call away at runtime. So for performance critical code, you may want to profile when using this technique.

Upvotes: 1

BadIdeaException
BadIdeaException

Reputation: 2124

Personally, I find the NPE one of the least helpful Exceptions, often wished it would at least give the name of the variable that was being accessed and was null. That being said, and given my general aversion to them, I would probably replace the NullPointerException with an IllegalStateException in your scenario.

Other than that, I think dropping the severity to warning as you have already said yourself is the most logical way. This may be my personal preference speaking, but to me a compile error is the compiler telling me "what you have done absolutely won't work" - that's why it goes on strike when it finds one. With null accesses, however, the compiler usually can't be sure, except in some construed cases - it even says it's a potential null access. So having this as a warning instead of an error makes more sense anyway.

Not at my most eloquent this morning so tl;dr: Errors="fatal", warnings="you'll live (barely)", potential null access isn't fatal, so drop it to warning.

Upvotes: 0

Related Questions