我有一个问题来处理NoSuchElementException
和NullPointerEception
。
我试图处理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
?
您可以使用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] 删除。
我来说两句