码迷,mamicode.com
首页 > 编程语言 > 详细

0801-----C++Primer听课笔记----------一个异常类

时间:2014-08-01 22:32:52      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   strong   io   for   

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(‘\n‘);
        }
    }
    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.运行结果

bubuko.com,布布扣

0801-----C++Primer听课笔记----------一个异常类,布布扣,bubuko.com

0801-----C++Primer听课笔记----------一个异常类

标签:style   blog   http   color   os   strong   io   for   

原文地址:http://www.cnblogs.com/monicalee/p/3885527.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!