Why should one use Objects.requireNonNull()?

前端 未结 11 1837
谎友^
谎友^ 2020-12-02 04:06

I have noted that many Java 8 methods in Oracle JDK use Objects.requireNonNull(), which internally throws NullPointerException if the given object

11条回答
  •  长情又很酷
    2020-12-02 04:52

    In addition to all the correct answers:

    We use it in reactive streams. Usually the resulting NullpointerExceptions are wrapped into other Exceptions depending on their occurance in the stream. Hence, we can later easily decide how to handle the error.

    Just an example: Imagine you have

     T parseAndValidate(String payload) throws ParsingException { ... };
     T save(T t) throws DBAccessException { ... };
    

    where parseAndValidate wrapps the NullPointerException from requireNonNull in a ParsingException.

    Now you can decide, e.g. when to do a retry or not:

    ...
    .map(this::parseAndValidate)
    .map(this::save)
    .retry(Retry.allBut(ParsingException.class))
    

    Without the check, the NullPointerException will occure in the save method, which will result in endless retries. Even worth, imagine a long living subscription, adding

    .onErrorContinue(
        throwable -> throwable.getClass().equals(ParsingException.class),
        parsingExceptionConsumer()
    )
    

    Now the RetryExhaustException will kill your subscription.

提交回复
热议问题