java - 如果是包装类,应该如何处理异常?

标签 java exception

假设我们有一个 Graph 类和另一个名为 GraphWrapper 的类。 Graph 类有一个名为 returnAdjVertices 的方法。

public List returnAdjVertices(int vertex) {
    if (vertex < 0 || vertex >= maxVertexCount) {
        throw exception
    }
}

现在我们在 GraphWrapper 中有一个包装函数,它可以计算顶点的度数

public static int getDegree(Graph graph, int vertex) {
    if (graph == null) throw new NullPointerException();
    if (vertext < 0 || vertex >= graph.maxVertexCount) throw exception // REDUNDANT

    return graph.returnAdjVertices(vertex).size();
}

现在,对 find Degree 的调用会检查顶点绑定(bind)条件两次。

这意味着我们正在进行冗余检查。在这种情况下,建议进行异常处理的最佳实践是什么?

最佳答案

您可以重新抛出异常(如果您没有在包装器中捕获它,它将自动完成)

public static int getDegree(Graph graph, int vertex) throws VertexOutOfBoundsException {
    return graph.returnAdjVertices(vertex).size();
}

或者将其捕获在包装器中并重新翻译为另一个

public static int getDegree(Graph graph, int vertex) throws WrapperException {
    int result;
    try {
        result = graph.returnAdjVertices(vertex).size();
    } catch (VertexOutOfBoundsException e) {
        throw new WrapperException();
    }
    return result;
}

或者甚至捕获它并尝试修复它

public static int getDegree(Graph graph, int vertex) {
    int result;
    try {
        result = graph.returnAdjVertices(vertex).size();
    } catch (VertexOutOfBoundsException e) {
        result = fixGraphAndReturnAdjVertices(graph, vertex);
    }
    return result;
}

您不应该再次进行检查,因为它真的很难维护。
变体的选择始终是情境性的。
当你的包装器与包装对象处于相同的抽象级别时,第一个变体(自动重新抛出)是很好的。
当包装器和包装对象处于不同的抽象级别时,第二种变体是很好的,作为一个例子,我可以建议使用 HDD 的对象的“FileNotFoundException”可以转换为尝试加载某些内容的对象的“CannotLoadDataException”之类的内容,如果它对于调用者来说,到底出了什么问题毫无意义。
当你的包装器可以修复问题时,第三种变体是很好的:)
所以这一切都取决于你。希望我的回答有帮助。

关于java - 如果是包装类,应该如何处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18253158/

相关文章:

java - 如何在 spring 上下文中更正 bean 的注入(inject)映射

java - 在 MySQL 表中存储多个用户日历

java - 我想在我的文件系统中保存多个数据

python - 如何断言运算符 < 和 >= 未实现?

magento - 如何在 Magento 数据库中启用 exception.log 和 system.log?

java - 如何解决clearcase中的 checkin 冲突问题

java - 对于两个整数用户输入,如何检测第一个输入是否传递了字符串?

java - Lotus Notes 代理 - 在数据库上注册代理

c# - 打印到基于非 xps 的打印机时 PrintQueue.AddJob 挂起

java - 从 JSP 抛出异常