简体   繁体   中英

How to throw an exception without an if construct

I have created a method that checks if there is an element in the list with a specific id, and if it does not exist it throws an exception. I just do not know how to check if the match value is false , then throw an my exception AccessToMessageForbiddenException.

private void validMessage(Long messageId) {
    List<Message> messageList = messageService.findBySender(1L);
    messageList.addAll(messageService.findByRecipient(1L));

    boolean match = messageList.stream().anyMatch(v -> messageId.equals(v.getId()));

    //How to throw an exception without an if construct
}

You can use findAny() instead of anyMatch , and throw an exception if the resulting Optional is empty.

This doesn't require an if statement. Just use orElseThrow() , which throws an exception if the Optional is empty:

private void validMessage(Long messageId) {
    List<Message> messageList = messageService.findBySender(1L);
    messageList.addAll(messageService.findByRecipient(1L));

    messageList.stream()
               .filter(v -> messageId.equals(v.getId()))
               .findAny()
               .orElseThrow(AccessToMessageForbiddenException::new);
}

You can get an optional of the Stream and use a consumer to throw an exception

Consumer<Message> d = t -> {
        throw new CustomException("Message: " + Message.toString());
 };


messageList.stream().filter(yourFilterPredicate).findAny().ifPresent(d);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM