C++ vector 异常处理 : Which one is the better way of throwing out_of_range() and why?

标签 c++ exception std stdvector

我想知道以下哪种在 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[x] 是未定义的行为,如果 x 超出范围,它不会抛出。您可以通过使用 at() ,正如@NeilButterworth 建议的那样。)

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

关于C++ vector 异常处理 : Which one is the better way of throwing out_of_range() and why?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42444768/

相关文章:

c++ - 模板特化适用于 gcc,但不适用于 visual studio 10

java - 如果 (arg1 > arg2) 应该满足,抛出什么异常?

c++ - std::string substr 方法问题

C++:当所有条目保证唯一时,std::map 的替代方案

c++ - 关于使用iostream进行解析的准则是什么?

使用线程时 C++ 应用程序性能会有所不同

c++ - 在 C++ 中检测 ENTER 键

java - 当传递给 main 的参数太多/太少时抛出异常

c++ - 内存中分配的 std::string 在哪里?

Java try finally 变体