1

I'm new to optionals and trying to understand why I'm receiving a null pointer exception at this line.

BottomObj bottomObj = new bottomObj();//initialized bottomObj

Optional<Location> location = Optional.ofNullable(bottomObj).map(obj -> obj.getRootObj()).map(rootObjLocation -> rootObjLocation.getLocation());

A BottomObj has a RootObj instance variable that is null in this case(as I have not set it and the constructor doesn't set it).

If I executed the line

RootObj rootObj = bottomObj.getRootObj();

I would get a null pointer exception. Thus, I'm trying to use the optional line above to deal with this scenario (ie where the bottomObj has no RootObj) to deal with the null pointer exception.

I've also tried this:

Optional<Location> location = Optional.ofNullable(bottomObj).map(obj -> obj.getRootObj()).map(rootObjLocation -> rootObjLocation.getLocation()).orElseThrow(etc...throw some exception...);

My program still crashes here every time on the getRootObj() function. Why is this happening? Shouldn't the optional deal with this?

Note, I know there are other tools I can use (such as a try catch block) to deal with this, but I'm specifically trying to understand optionals and implement the fix using their capabilities.

yalpsid eman
  • 3,064
  • 6
  • 45
  • 71
  • 1
    It's not `bottomObj` that's null. The `NullPointerException` is coming from somewhere inside `getRootObj`. Wrapping `bottomObj` itself in an `Optional` won't fix that. – user2357112 Feb 28 '17 at 18:59
  • 1
    Post a complete minimal example reproducing the problem. If bottomObj.getRootObj() throws an NPE, calling it inside a function passed to map() won't change anything. – JB Nizet Feb 28 '17 at 18:59
  • That's exactly the problem! getRootObj() throws an NPE. Is there no way to deal with this from the perspective of using an optional? – yalpsid eman Feb 28 '17 at 19:01
  • 3
    No! Optional is not intended to "trap" exceptions, it is just a way to get safer with null values. If you want to trap NPE, then use try/catch. – Jean-Baptiste Yunès Feb 28 '17 at 19:03
  • I understand now. Much appreciated – yalpsid eman Feb 28 '17 at 19:05

0 Answers0