首页 > 解决方案 > 美化函数中的异常处理

问题描述

这个功能可以吗?不美化?catch 子句可以留空吗,我听说它不赞成。

apiClient.accountList()是可能发生异常的地方。

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();
}

标签: javaexception

解决方案


如果您非常有动力避免重复的 return 语句,那么对控制流进行简单的调整就可以了。正如评论中提到的,记录异常通常是一个好主意。

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;
}

推荐阅读