[Muduo网络库源码分析] (4) base/Exception_cc_h_带 stack trace 的异常基类

来源:互联网 发布:手机恶作剧软件骑马 编辑:程序博客网 时间:2024/06/11 20:11

带 stack trace 的异常基类

实现:Exception


功能:实现对boost异常类的封装,可以有效存储异常


知识点:

  • int backtrace(void **buffer, int size);
    该函数用与获取当前线程的调用堆栈,获取的信息将会被存放在buffer中,它是一个指针数组。参数 size 用来指定buffer中可以保存多少个void* 元素。函数返回值是实际获取的指针个数,最大不超过size大小在buffer中的指针实际是从堆栈中获取的返回地址,每一个堆栈框架有一个返回地址。
  • char **backtrace_symbols(void *const *buffer, int size);
    backtrace_symbols将从backtrace函数获取的信息转化为一个字符串数组. 参数buffer应该是从backtrace函数获取的数组指针,size是该数组中的元素个数(backtrace的返回值),函数返回值是一个指向字符串数组的指针,它的大小同buffer相同.每个字符串包含了一个相对于buffer中对应元素的可打印信息.它包括函数名,函数的偏移地址,和实际的返回地址
  • void backtrace_symbols_fd(void *const *buffer, int size, int fd);
    backtrace_symbols_fd与backtrace_symbols 函数具有相同的功能,不同的是它不会给调用者返回字符串数组,而是将结果写入文件描述符为fd的文件中,每个函数对应一行.它不需要调用malloc函数,因此适用于有可能调用该函数会失败的情况。

  • Boost::exception类使用


用途:

用于异常的抛出和记录

代码及分析:

Exception.h

// Use of this source code is governed by a BSD-style license// that can be found in the License file.//// Author: Shuo Chen (chenshuo at chenshuo dot com)#ifndef MUDUO_BASE_EXCEPTION_H#define MUDUO_BASE_EXCEPTION_H#include <muduo/base/Types.h>#include <exception>namespace muduo{//重载boost库中的exception基类class Exception : public std::exception{ public:  explicit Exception(const char* what);//构造函数  explicit Exception(const string& what);//重载构造函数  virtual ~Exception() throw();//析构函数  virtual const char* what() const throw();//返回出错信息  const char* stackTrace() const throw();//返回堆栈信息 private:  void fillStackTrace();//存储堆栈信息  string message_;//用来存储出错信息  string stack_;//用来存储堆栈信息};}#endif  // MUDUO_BASE_EXCEPTION_H

Exception.cc

// Use of this source code is governed by a BSD-style license // that can be found in the License file.//// Author: Shuo Chen (chenshuo at chenshuo dot com)#include <muduo/base/Exception.h>//#include <cxxabi.h>#include <execinfo.h>#include <stdlib.h>using namespace muduo;//构造函数Exception::Exception(const char* msg)  : message_(msg){  fillStackTrace();}//构造函数Exception::Exception(const string& msg)  : message_(msg){  fillStackTrace();}//析构函数Exception::~Exception() throw (){}//返回出错信息const char* Exception::what() const throw(){  return message_.c_str();}//返回堆栈信息const char* Exception::stackTrace() const throw(){  return stack_.c_str();}void Exception::fillStackTrace(){  const int len = 200;  void* buffer[len];  //该函数用与获取当前线程的调用堆栈  int nptrs = ::backtrace(buffer, len);  //backtrace_symbols将从backtrace函数获取的信息转化为一个字符串数组  char** strings = ::backtrace_symbols(buffer, nptrs);  if (strings)  {    for (int i = 0; i < nptrs; ++i)    {      // TODO demangle funcion name with abi::__cxa_demangle      stack_.append(strings[i]);      stack_.push_back('\n');    }    free(strings);  }}
阅读全文
0 0
原创粉丝点击