How to trace a NullPointerException in a chain of getters

后端 未结 11 1545
谎友^
谎友^ 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:48

    The answer depends on how you view (the contract of) your getters. If they may return null you should really check the return value each time. If the getter should not return null, the getter should contain a check and throw an exception (IllegalStateException?) instead of returning null, that you promised never to return. The stacktrace will point you to the exact getter. You could even put the unexpected state your getter found in the exception message.

提交回复
热议问题