JonB
JonB

Reputation: 814

Prettifying exception handling in function

Can this func. not be prettified? Can the the catch clause be left empty, I have heard it's frowned up on.

apiClient.accountList() is where the exception can occur.

public Optional<Account> getAccount(String accountUuid) throws ApiException {
    try {
        for (Account account : apiClient.accountList()) {
            if (account.getUuid().equals(accountUuid)) {
                return Optional.of(account);
            }
        }
    } catch (ApiException e) {
        return Optional.empty();
    }
    return Optional.empty();
}

Upvotes: 0

Views: 54

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109597

You can use Stream, assuming getUuid does not throw an ApiException.

public Optional<Account> getAccount(String accountUuid) throws ApiException {
    try {
        return apiClient.accountList().stream()
            .filter(account -> account.getUuid().equals(accountUuid))
            .findAny();
    } catch (ApiException e) {
        /* Log exception */
        return Optional.empty();
    }
}

Actually instead of collection returning methods like accountList() it more and more makes sense to use Streams, accountStream().

Upvotes: 1

user11595728
user11595728

Reputation:

If you're very motivated to avoid the duplicate return statement, a simple tweak to the control-flow should do it. As mentioned in the comments, logging exceptions is often a good idea.

public Optional<Account> getAccount(String accountUuid) throws ApiException {
    Optional<Account> result = Optional.empty();
    try {
        for (Account account : apiClient.accountList()) {
            if (account.getUuid().equals(accountUuid)) {
                result = Optional.of(account);
                break;
            }
        }
    } 
    catch (ApiException e) { /* Log exception */ }
    return result;
}

Upvotes: 2

Related Questions