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

来源:互联网 发布:mynba2k18网络维护中 编辑:程序博客网 时间:2024/06/06 04:04
  • 异常类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();}
原创粉丝点击