如何在流Java 8中处理NoSuchElementException和NullPointerException

Gusti Bimo Marlawanto:

我有一个问题来处理NoSuchElementExceptionNullPointerEception

我试图处理NoSuchElementException此代码中的错误:

public Item shop(ItemShopParam itemShopParam) {
    String orderNumber = itemShopParam.getOrderNumber();
    Shipment shipment = shipmentService.findByNumber(orderNumber);

    Item item = findBySku(shipment.getId(), itemShopParam.getItemSku());
    Job job = item.getShipment().getJobs().stream().filter(j -> j.getType().equals(Job.Type.RANGER)).findFirst().get();
    checkJobState(job);

  private void checkJobState(Job job) {
    if (job.getState() == Job.State.INITIAL)
        throw new JobNotStartedException();
    if (job.getState() == Job.State.FINISHED)
        throw new JobAlreadyFinishedException();
}

通过替换get()Optional().orElse(null)但是,它返回了另一个错误异常NullPointerException我知道为什么会这样,因为checkJobState检查null值为job

枚举状态:

public enum State {
    INITIAL(0),
    STARTED(1),
    LAST_ITEM_PICKED(2),
    FINALIZING(3),
    ACCEPTED(4),
    DELIVERING(5),
    FOUND_ADDRESS(6),
    FINISHED(7),
    FAILED(8);

避免NoSuchElementException无回报的最佳做法是什么NullPointerException

SK:

您可以使用Optional.isPresent()检查:

Optional<Job> maybeJob = item.getShipment().getJobs().stream().filter(j -> j.getType().equals(Job.Type.RANGER)).findFirst();
if(maybeJob.isPresent()) {
    checkJobState(job);
}

甚至更好ifPresent()

Optional<Job> maybeJob = item.getShipment().getJobs().stream().filter(j -> j.getType().equals(Job.Type.RANGER)).findFirst().ifPresent(job -> checkJobState(job));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章