我们的服务调用一个从数据库中检索数据的API。让我们这样定义它
public List< RowData > getData(int id)抛出FinderException
看着这个接口,我想它会在找不到数据时抛出FinderException。所以,我的代码是:
try{
List<RowData> list = getData(id);
} catch (FinderException e) {
throw new InternalException();
}
return list;
现在,我意识到当找不到数据时,API不会抛出FinderException。因此,我的客户的代码正在崩溃。因为我们的应用程序接口的客户端期望在找不到数据时抛出InternalException。现在,他们的代码
list.get(0)
正在崩溃。现在,我正在考虑将代码更改为:
try{
List<RowData> list = getData();
if(list.isEmpty()) throw new FinderException()
} catch (FinderException e) {
throw new InternalException();
}
return list;
这是在同一个方法中抛出和捕获的好代码吗?若否,原因何在?如何改进我的设计?
发布于 2018-12-12 06:01:20
您应该分别处理这两种情况:
List<RowData> list;
try {
list = getData();
if(list.isEmpty()) throw new NoItemsFoundException();
// handle this elsewhere, maybe the same place you handle InternalException
} catch (FinderException e) {
throw new InternalException(e.getMessage());
}
return list;
将捕获的FinderException的消息传递给重新抛出的InternalException是一种好的做法,这样就不会丢失任何信息。
https://stackoverflow.com/questions/53731953
复制相似问题