哪个向量抛出了索引超出范围的异常

Which vector threw index out of range exception?

本文关键字:范围 异常 索引 向量      更新时间:2023-10-16

我想访问对抛出超出范围异常的std::vector的引用,或者至少是抛出异常的行号(类似于Java的堆栈跟踪)。下面是一个示例程序:

#include <iostream>
#include <vector>
std::vector<int> vec1;
std::vector<int> vec2;
vec1.push_back(1);
vec2.push_back(2);
try
{
    std::cout << vec1.at(1) << std::endl;
    std::cout << vec2.at(1) << std::endl;
}
catch(Exception e)
{
    // e.lineNumber()? e.creator_object()?
    std::cout << "The following vector is out of range: " << ? << std::endl;
    // or...
    std::cout << "There was an error on the following line: " << ? << std::endl;
}

我知道这个例子是微不足道的,但我希望它展示了我正在寻找的功能。

编辑:Implementation, from g++——version: g++ (GCC) 4.1.2 20071124 (Red Hat 4.1.2-42)

你需要自己做:

#include <iostream>
#include <vector>
std::vector<int> vec1;
std::vector<int> vec2;
vec1.push_back(1);
vec2.push_back(2);
try
{
    std::cout << vec1.at(1) << std::endl;
}
catch(std::exception& e)
{
    std::cout << "The following vector is out of range: " << "vec1" << std::endl;
}
try
{
    std::cout << vec2.at(1) << std::endl;
}
catch(std::exception& ex)
{
    std::cout << "The following vector is out of range: " << "vec2" << std::endl;
}