Search code examples
java-8guavapreconditions

Java 8 Guava Preconditions throwing NullPointerException while evaluating the exception message string


I have an object myObject and I want to make sure that it is null or else I want to print a custom message with the object's id. I have the following line of code trying to achieve the same

Preconditions.checkArgument(Objects.isNull(myObject),
                        "This object is not null #%s.", myObject.getId());

This condition works fine when myObject is not null. It throws the appropriate exception message. But when the object is indeed null, it was my expectation that the rest of the code would be executed but instead, I get a null pointer exception because of myObject.getId() call.

Do guava preconditions evaluate the exception message string regardless of whether the condition is true or not?


Solution

  • With

    Preconditions.checkArgument(Objects.isNull(myObject),
                        "This object is not null #%s.", myObject.getId());
    

    you have to look what happens in which order:

    Before any call to checkArgument() can occur, all arguments to it are evaluated:

    • Objects.isNull(myObject)
    • the string
    • myObject.getId()

    Only then the call can occur, and if an exception occurs during this evaluation, the call doesn't happen at the first place.

    Just for completeness, as it was already mentioned elsewhere: the way to go would be myObject == null ? null: myObject.getId(), as it avoids the dereferencing in the case of a null object.