Analysis of muduo library - base (3) Exception

Exception class is used to store and obtain exception data

head File

#ifndef MUDUO_BASE_EXCEPTION_H
#define MUDUO_BASE_EXCEPTION_H

#include <muduo/base/Types.h>
#include <exception>

namespace muduo
{

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(); //return exception data stack

 private:
  void fillStackTrace();

  string message_;
  string stack_;
};

}

cpp file

#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(); //Return the current exception content pointer
}

const char* Exception::stackTrace() const throw()
{
  return stack_.c_str(); //Return all exception content pointers
}

void Exception::fillStackTrace()
{
  const int len ​​= 200;
  void* buffer[len];
  int nptrs = ::backtrace(buffer, len); //system call, used to return the total number of calls to the function that sent the exception and the previous function, and store a list of its function pointers
  char** strings = ::backtrace_symbols(buffer, nptrs);//Return the function pointer list query as a specific function information string
  if (strings)
  {
    for (int i = 0; i < nptrs; ++i) //String split and merged into stack
    {
      // TODO demangle function name with abi::__cxa_demangle
      stack_.append(strings[i]);
      stack_.push_back('\n');
    }
    free(strings);
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325801465&siteId=291194637