在流中抛出自定义异常

时间:2017-11-21 10:20:28

标签: java exception java-stream

当没有找到FriendNotFoundExceptionfirstName的人时,我需要在我的代码中抛出lastName是否可以在Stream中捕获异常?

现在我有类似的东西,但它失败了。

@Override
public Friend findFriend(String firstName, String lastName) throws FriendNotFoundException { 
    if (firstName == null || lastName ==null) {
        throw new IllegalArgumentException("There are no parameters");
    }
    if (friends.stream().filter(x -> !firstName.equals(x.getLastName()) && 
        (!lastName.equals(x.getLastName()))) != null);
    {
        throw new FriendNotFoundException(firstName, lastName);
    }

    return friends.stream().filter(
        x -> (firstName.equals(x.getFirstName())) && 
        (lastName.equals(x.getLastName()))).findAny().orElse(null);                     
}

1 个答案:

答案 0 :(得分:5)

答案是:

TestFixtureTearDown

顺便说一下,让代码更优雅,我的主张就是做这样的事情:

return friends.stream()
            .filter(x -> (firstName.equals(x.getFirstName())) && 
             (lastName.equals(x.getLastName())))
            .findAny()
            .orElseThrow(() -> new FriendNotFoundException(firstName, lastName))