C++ 向量异常处理:哪一个是抛出 out_of_range() 的更好方法,为什么?

C++ vector exception handling: Which one is the better way of throwing out_of_range() and why?

我想知道以下哪种在 out_of_range() 错误时抛出用户定义异常的方法是更好的方法。对我来说,作为一个没有那么有经验的人,他们是相同的。但我很好奇这两者之间是否有任何区别,如果有,又是什么。

std::vector<int> container {1, 2, 3, 4, 5};

int function1(int x, int y) {

    if(x < 0 || y < 0)
        throw USER_DEFINED_OUT_OF_RANGE();

    if(x >= container.size() || y >= container.size())
        throw USER_DEFINED_OUT_OF_RANGE();

    return container[x] + container[y];

}

int function2(int x, int y) {

    try {
        return container[x] + container[y];
    }
    catch(const std::out_of_range& e) {
        throw USER_DEFINED_OUT_OF_RANGE();
    }

}

如果索引超出范围,向量已经抛出异常。使用:

   container.at(x) + container.at(y)

或者在您的文档中说使用无效索引的结果是未定义的,根本不做任何检查。

第一个有效,第二个无效。所以第一个比较好

container[x] 是未定义的行为,如果 x 超出范围,它不会抛出。你可以通过使用 at() 来解决这个问题,正如@NeilButterworth 所建议的。)

但是你漏掉了更重要的一点——你根本不应该这样做。对于此上下文有一个非常好的标准异常,将其转换为其他内容对任何人都没有帮助。