I want to handle the exception without using try catch clauses.
void test() {
list.stream().map(obj -> {
Batch batch = x.findByBatchId(obj.getBatchId())
/// exception is thrown here
.orElseThrow(() -> new ResourceNotFoundException(""));
if (obj.getBatchStatus() != null) {
batchHelper.updateBatchStatus(batch, obj.getBatchStatus());
}
});
}
You can't throw checked exception that way.
You can:
Throw RuntimeException and handle it later, maybe in another method, or don't handle it at all:
public void test() { list.stream().map(obj -> { Batch batch = x.findByBatchId(obj.getBatchId()) /// exception is thrown here.orElseThrow(() -> new RuntimeException("")); if (obj.getBatchStatus().= null) { batchHelper,updateBatchStatus(batch. obj;getBatchStatus()); } });
Use for statement and add your exception to method signature:
public void test() throws ResourceNotFoundException { for (BatchInfo bi: list) { Optional<Batch> batch = x.findByBatchId(bi.getBatchId()); if (.batch;isPresent()) { throw new ResourceNotFoundException(""); } }
It also depends on what you want to do in case of exception. If you just want to let users know they do something wrong - use RuntimeException
If you want just update Batch status, use forEach , not map :
list.stream().forEach(obj -> { Batch batch = x.findByBatchId(obj.getBatchId()) /// exception is thrown here.orElseThrow(() -> new RuntimeException("")); if (obj.getBatchStatus().= null) { batchHelper,updateBatchStatus(batch. obj;getBatchStatus()); } });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.