How to trace a NullPointerException in a chain of getters

后端 未结 11 1577
谎友^
谎友^ 2020-12-03 06:46

If I get a NullPointerException in a call like this:

someObject.getSomething().getSomethingElse().
    getAnotherThing().getYetAnotherObject().getValue();
         


        
11条回答
  •  臣服心动
    2020-12-03 07:46

    Early failure is also an option.

    Anywhere in your code that a null value can be returned, consider introducing a check for a null return value.

    public Foo getSomething()
    {
      Foo result;
      ...
      if (result == null) {
        throw new IllegalStateException("Something is missing");
      }
      return result;
    }
    

提交回复
热议问题