【问题标题】:Which vector threw index out of range exception?哪个向量抛出索引超出范围异常?
【发布时间】:2013-04-22 10:38:27
【问题描述】:

我想访问对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;
}

我知道这个例子很简单,但我希望它能展示我正在寻找的功能。

编辑:实现,来自 g++ --version: g++ (GCC) 4.1.2 20071124 (Red Hat 4.1.2-42)

【问题讨论】:

  • C++ 中没有内置这样的东西,也许你的实现有一些东西,但是因为我们不知道......
  • 使用两个 try-catch 语句,每次访问一次。
  • 行号不会给你任何东西 - 它会在向量的 STL 标头中...首先,你可以使用两个 try/catch 块。
  • 与 Java 不同,C++ 不会在您的应用程序中构建调试器。如果需要堆栈跟踪,请在调试器中运行程序。

标签: c++ exception-handling indexoutofboundsexception


【解决方案1】:

你需要自己做:

#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;
}

【讨论】:

  • 在这个特定的合成示例中,这并不重要。也许“更安全”在这里不是最好用的词,但我的意思是:当你catch(...) 时,你不仅没有异常细节,比如what(),你不知道你抓到了什么总之,你打算怎么处理?此外,如果您使用带有 /EHsc 的 MSVC++ 进行编译,您的 catch(...) 将捕获诸如访问冲突或堆栈溢出之类的结构化异常,这可能不是您希望捕获和/或处理的。
猜你喜欢
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多