10

Compiling the following with MinGW 4.6.2 (with g++ -g -std=c++0x), gdb doesn't seem to want catch the std::out_of_range if I try catch throw. if I throw it manually it catches fine, am I doing something wrong?

#include <stdexcept>
#include <vector>

int main()
{
    std::vector<char> vec(10);
    try {       
        vec.at(10); // this won't be caught by gdb

        // throw std::out_of_range(""); // this will
    }
    catch (std::out_of_range const& e) {        
    }   
}
0

4 Answers 4

4

Add a breakpoint where std::vector throws the exception. At this moment, no stack unwinding has occured yet so you should be able to fully backtrace to the original statement.

I was able to achieve this, but only in a very implementation-defined way:

1) Locate the vector's range checking function in stl_vector.h:

_M_range_check(size_type __n) const
{
    if (__n >= this->size())
          __throw_out_of_range(__N("vector::_M_range_check"));
}

2) Add a breakpoint to the line where __throw_out_of_range() is called. Note: I tried adding a breakpoint by 'break __throw_out_of_range' but this did not work. Instead, I need to hardcode the breakpoint with it's file and line number (break stl_vector.h:794). You can add this to your .gdbinit file to have gdb break on all failed range checks.

2
  • Good catch. Now adding a break point in QtCreator seems to work. Aug 5, 2019 at 11:18
  • 2
    Thanks. I found in modern gdbs (8.3) break __throw_out_of_range works without file::line; used for std::unordered_map. The standard catch throw std::out_of_range still does not.
    – FDS
    Mar 27, 2020 at 11:55
3

As you've seeen, the exception from std::vector::at() is thrown by __throw_out_of_range which is a function inside libstdc++.so, so I suspect there's some problem on Mingw that prevents GDB from setting a catchpoint in a shared library. Or maybe your libstdc++ wasn't built with -g.

If your GCC was configured with --enable-libstdcxx-debug you would have a second set of libs built with -O0 -g that might work better when debugging, but that option isn't used often.

0
2

You are not actually catching exception in gdb. Try catch catch to catch exception.

0
2

I had this issue with msys2/mingw64 and setting this breakpoint made gdb stop where the throw occurred:

(gdb) b std::__throw_out_of_range_fmt

it also works with other exceptions, e.g. to catch std::bad_function_call exception, use this:

(gdb) b std::__throw_bad_function_call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.