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

  • 异常类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();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章