Find Where a C++ Exception is Thrown

January 30, 2014
Here's a simple example of how to find where a C++ exception is thrown using gdb. There's no need to instrument your code or create a special exception class that keeps track of the file and line number of where it's thrown. After all, throwing an exception should be an exceptional case and not done very often.
Exceptions provide a way to react to exceptional circumstances (like runtime errors) in programs by transferring control to special functions called handlers.

Here's an example throw_exception.cpp.
#include <iostream>
#include <stdexcept>
 
using namespace std;
 
void function()
{
   throw runtime_error("i am an exception");
}
 
int main()
{
   try
   {
      function();
   }
   catch(const std::exception& e)
   {
      cout << e.what() << endl;
   }
 
   return 0;
}
The makefile for it.
all: throw_exception
 
throw_exception : throw_exception.cpp
        $(CXX) -g $< -o $@
Here's how to use catch throw in gdb.
~/exception$ make
g++ -g throw_exception.cpp -o throw_exception
~/exception$ gdb throw_exception
...
Reading symbols from throw_exception...done.
(gdb) catch throw
Catchpoint 1 (throw)
(gdb) run
Starting program: throw_exception
Catchpoint 1 (exception thrown), 0x00007ffff7b8f910 in __cxa_throw () from /usr/lib/libstdc++.so.6
(gdb) where
#0  0x00007ffff7b8f910 in __cxa_throw () from /usr/lib/libstdc++.so.6
#1  0x0000000000400d89 in function () at throw_exception.cpp:8
#2  0x0000000000400dca in main () at throw_exception.cpp:15
(gdb)

Related Posts