1.exception.h
#ifndef __EXCEPTION_H__ #define __EXCEPTION_H__ #include <exception> #include <string> class Exception : public std::exception{ public: Exception(const char *); Exception(const std::string &); virtual ~Exception() throw();//表示这个函数不抛出异常 virtual const char * what() const throw(); const char* stackTrace()throw(); private: void fillStackTrace();// std::string message_; //异常的名字 std::string stack_; //栈痕迹 }; #endif
2.exception.cpp
#include "exception.h" #include <execinfo.h> #include <stdlib.h> Exception::Exception(const char *s) :message_(s) { fillStackTrace(); } Exception::Exception(const std::string &s) :message_(s) { fillStackTrace(); } Exception::~Exception() throw() { } const char * Exception::what() const throw(){ return message_.c_str(); } void Exception::fillStackTrace(){ const int len = 200; void * buffer[len]; // 获取栈痕迹 存储在buffer数组中,这里len是数组的最大长度,而返回值nptrs是数组的实际长度 int nptrs = ::backtrace(buffer, len); //把buffer中的地址转化成字符串存储在strings中 //这里在生成strings的时候调用了malloc函数 动态分配了内存 因此后面需要free char** strings = ::backtrace_symbols(buffer, nptrs); if(strings){ int i; for(i = 0; i < nptrs; i++){ stack_.append(strings[i]); stack_.push_back(' '); } } free(strings); } const char *Exception::stackTrace() throw(){ return stack_.c_str(); }
3.test_exception.cpp
#include "exception.h" #include <iostream> using namespace std; void foo(){ throw Exception("foobar"); } void bar(){ foo(); } int main(int argc, const char *argv[]) { try{ bar(); } catch(Exception &e){ cout << "reason: " << e.what() << endl; cout << "stack trace: " << e.stackTrace() << endl; } return 0; }
4.运行结果