zoukankan      html  css  js  c++  java
  • 0801-----C++Primer听课笔记----------一个异常类

    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.运行结果

  • 相关阅读:
    memcached +mysql+php 例子
    PHP利用memcache缓存技术提高响应速度
    实现QQ第三方登录教程(php)
    php如何解决多线程同时读写一个文件的问题
    php数组函数常见的那些
    PHP 5种方式获取文件后缀名
    函数与方程
    函数图像习题
    高中数学中需要重点关注的函数和图像
    特殊分段函数的图像画法
  • 原文地址:https://www.cnblogs.com/monicalee/p/3885527.html
Copyright © 2011-2022 走看看