javanullnullpointerexception

NotNull for method return values


I am seeing a piece of code like this, im simplifying it for explaining ==

import org.jetbrains.annotations.NotNull;


public class TestClass {
  @NotNull StringBuffer met1(Integer a) {
     
        if ( a == 3)
            throw new RuntimeException();
        return new StringBuffer("this");
    }

    public static void main(String[] args) {
        TestClass m = new TestClass();
    
        StringBuffer mmm = m.met1(3);


    }
}

Does this piece of code look good. The method can potentially return a null value. It is thus violating its public contract. Isnt so?


Solution

  • The method can potentially return a null value.

    No, it can't. It can throw an exception, but then no value is returned at all. The exception is thrown instead.

    For example, this code would safe from a NullPointerException being thrown by the second line:

    StringBuffer mmm = m.met1(3);
    System.out.println(mmm.length());
    

    There is no way that mmm will have a null value after the first line, causing a NullPointerException in the second line. It might not get to the end of the first line (due to RuntimeException being thrown), but that's a different matter.

    @NotNull doesn't assert "this method will never throw an exception" - it asserts "if this method completes normally, it will never return a null value".