C++ 获取 std::out_of_range 异常的位置

标签 c++ debugging exception

我正在编写一个相当冗长的程序,在正常运行一段时间后,我突然得到:

terminate called after throwing an instance of 'std::out_of_range'
 what(): basic_string::substr

作为异常处理的新手,我做了一些研究,发现通过将以下内容添加到我的主要功能,我可能会获得更多信息:

int main(int argc, char **argv){
    try{
        //stuff
    }
    catch(exception const &exc){
        cerr << "Caught exception: " << exc.what() << endl;
    }
}

结果如下:

Caught exception: basic_string::substr

这并不比默认输出更有用;它没有告诉我任何关于触发核心转储的行(我的程序中有很多 substr 调用)、substr 试图处理的数据等。是否有一种方法可以在 C++ 中显示此类信息,或者使用 gdb 等调试器是我唯一的选择吗?

最佳答案

有几种方法。

  1. 如您所说,调试器 - 但一旦代码投入生产,它就无济于事。

  2. 嵌套异常和函数 try block 。例如:

#include <exception>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <iomanip>

void bar(std::string& s, int i)
try
{
    s.at(i) = 'A';
}
catch(...)
{
    std::ostringstream ss;
    ss << "error in bar(" << std::quoted(s) << ", " << i << ")";
    std::throw_with_nested(std::runtime_error(ss.str()));
}

void foo(std::string& s)
try
{
    bar(s, 6);
}
catch(...)
{
    std::ostringstream ss;
    ss << "error in foo(" << std::quoted(s) << ")";
    std::throw_with_nested(std::runtime_error(ss.str()));
}

void stuff()
try
{
    std::string s;
    foo(s);
}
catch(...)
{
    std::throw_with_nested(std::runtime_error("error in stuff()"));
}

void print_exception(std::ostream& os, const std::exception& e, int level =  0)
{
    os << std::string(level, ' ') << "exception: " << e.what() << '\n';
    try {
        std::rethrow_if_nested(e);
    } catch(const std::exception& e) {
        print_exception(os, e, level+1);
    } catch(...) {}
}

int main()
{
    try{
        stuff();
    }
    catch(std::exception& e)
    {
        print_exception(std::cerr, e);
        return 127;
    }
    return 0;
}

示例输出:

exception: error in stuff()
 exception: error in foo("")
  exception: error in bar("", 6)
   exception: basic_string::at: __n (which is 6) >= this->size() (which is 0)
  1. 您可以使用 boost::stacktrace 代替上面的嵌套异常处理。

http://coliru.stacked-crooked.com/a/f21bd35632a0a036

关于C++ 获取 std::out_of_range 异常的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49548846/

相关文章:

c++ - 运算符重载如何在 cpp 中进行排序?

python - 无法在 Visual Studio Code 中调试 Django 单元测试

java - 转储执行 - java?

c# - mono 的 mdb 文件与 csc 的 pdb 文件

java - 处理 JSONObject 异常

C++ 模板参数包自动将 & 添加到其参数

c++ - (C++) 试图完成一个快速程序,但我不确定哪里出错了?

c++ - 是否有任何具有非 IEEE C/C++ 浮点格式的现代平台?

java - 无法抛出 IllegalArgumentException

java - 我怎样才能 "retry" try catch ?