首页 > 编程语言 >gdb 打印出错行 Find Where a C++ Exception is Thrown

gdb 打印出错行 Find Where a C++ Exception is Thrown

时间:2023-02-02 15:23:24浏览次数:52  
标签:Thrown thrown Exception exception C++ gdb cpp where throw

https://www.digitalpeer.com/blog/find-where-a-cpp-exception-is-thrown

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

把空格按成4个tab
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)

如果没有打印行 编译参数加上 -ggdb

标签:Thrown,thrown,Exception,exception,C++,gdb,cpp,where,throw
From: https://www.cnblogs.com/marklove/p/17086110.html

相关文章