在Java中的同一方法中引发和捕获异常
我们的服务正在调用从数据库检索数据的API。让我们这样定义它 public List在Java中的同一方法中引发和捕获异常,java,oop,exception-handling,coding-style,Java,Oop,Exception Handling,Coding Style,我们的服务正在调用从数据库检索数据的API。让我们这样定义它 public ListgetData(int-id)抛出FinderException 看看这个API,我认为它会在找不到数据时抛出FinderException。所以,我的代码是:- try{ List<RowData> list = getData(id); } catch (FinderException e) { throw new InternalException(); } return li
try{
List<RowData> list = getData(id);
} catch (FinderException e) {
throw new InternalException();
}
return list;
正在破裂。
现在,我正在考虑将代码更改为:-
try{
List<RowData> list = getData();
if(list.isEmpty()) throw new FinderException()
} catch (FinderException e) {
throw new InternalException();
}
return list;
试试看{
List=getData();
if(list.isEmpty())抛出新的FinderException()
}捕获(发现异常e){
抛出新的InternalException();
}
退货清单;
在同一个方法中抛出和捕获这段代码好吗?若否,原因为何。
如何改进我的设计?您应该分别处理这两种情况:
列表;
试一试{
list=getData();
if(list.isEmpty())抛出新的noItemsFundException();
//在其他地方处理这个问题,可能是在处理内部异常的同一个地方
}捕获(发现异常e){
抛出新的InternalException(例如getMessage());
}
退货清单;
将捕获到的FinderException的消息传递给rethrown InternalException是一种很好的做法,因此不会丢失任何信息。InternalException是我理解的NoItemsFundeException,但我仍然会区分这两种情况:1。未找到项目,2。api错误。如果您真的只想处理1个异常,那么是的,您可以执行您提出的解决方案。捕获一个异常并重新显示另一个异常是可以的,但是最好将原始消息传递给新的异常。
try{
List<RowData> list = getData();
if(list.isEmpty()) throw new FinderException()
} catch (FinderException e) {
throw new InternalException();
}
return list;
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;