java - 美化函数中的异常处理
问题描述
这个功能可以吗?不美化?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();
}
解决方案
如果您非常有动力避免重复的 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;
}
推荐阅读
- nlp - 无法使用 Allennlp 双仿射解析器模型
- prolog - 如何使用递归在序言中打印星形三角形
- html - Google Docs Viewer 嵌入式 PDF 并不总是显示出来
- php - php连接不上数据库
- debezium - Debezium 服务器在应用程序的处理程序方法中出现错误后停止连接器:意外的数据类型“null”,错误 =“{}”
- nginx - 你能教我吗?这意味着 nginx-vod-module 位置 ~ ^/p/\d+/(sp/\d+/)?serveFlavor/
- python - 如何在不遍历两个 Pandas DataFrames 的情况下确定组中最接近另一个日期的日期?
- asp.net-identity - 如何将常规 asp.net 身份用于 Blazor 应用程序?
- python - 使用队列的非二叉树中的 BFS / 级别顺序遍历
- esper - Esper 语句检查,如果 A 后跟 B 没有任何其他 As 介于两者之间