【问题标题】:Throwing and catch an exception in the same method in Java在Java中的同一方法中抛出和捕获异常
【发布时间】:2018-12-11 20:33:47
【问题描述】:

我们的服务正在调用从数据库中检索数据的 API。让我们这样定义它

public List getData(int id) 抛出 FinderException

看这个API,我以为找不到数据的时候会抛出FinderException。所以,我的代码是:-

try{
    List<RowData> list = getData(id);
} catch (FinderException e) {
     throw new InternalException();
}
return list;

现在,我意识到当找不到数据时,API 不会抛出 FinderException。因此,我的客户的代码正在破坏。因为我们 API 的客户端期望在找不到数据时抛出 InternalException。现在,他们的代码

list.get(0)

正在崩溃。 现在,我正在考虑将代码更改为:-

try{
    List<RowData> list = getData();
    if(list.isEmpty()) throw new FinderException()
} catch (FinderException e) {
     throw new InternalException();
}
return list;

这是在同一方法中抛出和捕获的好代码吗?如果不是,为什么。 如何改进我的设计?

【问题讨论】:

    标签: java oop exception-handling coding-style


    【解决方案1】:

    你应该分别处理这两种情况:

    1. 您的 API 的 FinderException(无论出于何种原因抛出该异常,可能是底层服务不可用或其他原因)。
    2. 未找到任何项目(我建议您创建自己的(内部)NoItemsFoundException 或类似的东西)

    ``

    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 是一种很好的做法,因此不会丢失任何信息。

    【讨论】:

    • InternalException 是 NoItemsFoundException
    • 我明白,但我仍然会区分这两种情况:1. 找不到项目,2. api 错误。如果您真的只想处理 1 个异常,那么可以,您可以执行您提出的解决方案。捕获一个异常并重新抛出一个不同的异常是可以的,但是最好将原始消息传递给您的新异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    相关资源
    最近更新 更多