muduo库源码分析(3):异常类

本文介绍C++中如何使用backtrace函数获取调用栈信息,并通过fillStackTrace函数收集线程栈信息,最终实现异常类Exception的定义,包括如何记录异常信息及堆栈信息。
  • 异常类Exception
    前言:
#include <execinfo.h>
int backtrace(void** buffer,int size);
buffer:是一个指针数组,数组中存放的是调用过的函数地址
buffer----->    ---------------
                |  调用函数地址  |    
                ---------------
                |              |
                ---------------
                |              |
                ---------------
返回值:数组中存放的元素的个数

char** backtrace_symbols(void* const *buffer,int size);
将调用的函数地址转换成字符串
返回值:指针数组,数组中的元素是函数地址对应的字符串(编译期已确定)
注意:这里的数组是由malloc分配出来的,所以我们需要手动释放该数组内存,而数组中指向的字符串有系统释放。
重要函数:fillStackTrace()
// 获取线程栈信息
void Exception::fillStackTrace()
{
  const int len = 200;
  void* buffer[len];
  int nptrs = ::backtrace(buffer, len);
  char** strings = ::backtrace_symbols(buffer, nptrs);
  if (strings)
  {
    for (int i = 0; i < nptrs; ++i)
    {
      stack_.append(strings[i]);
      stack_.push_back('\n');
    }
    free(strings);
  }
}
  • 异常类定义(其他成员函数没什么难点)
    explicit :修饰的构造函数只能显示初始化
    成员函数加throw():该函数不抛出异常
class Exception : public std::exception
{
 public:
  explicit Exception(const char* what):message_(what)
  {
      fillStackTrace();
  }
  explicit Exception(const string& what)
  :message_(what)
  {
      fillStackTrace();
  }
  virtual ~Exception() throw(){};
  virtual const char* what() const throw();
  const char* stackTrace() const throw()
  {
      return stack_.c_str();
  }

 private:
  void fillStackTrace();
  string message_;// 保存异常信息 
  string stack_;// 保存堆栈信息
};
const char* Exception::what() const throw()
{
  return message_.c_str();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值