muduo源码解析4-exception类

exception

class exception:public std::exception
{
};

作用:

实现了一个异常类,继承于std::exception,主要用于实现打印线程调用栈信息.

成员变量:

private:
    string m_message;
    string m_stack;

主要含有异常消息以及线程栈信息两个数据成员,

调用栈信息通过currentthread::stackTrace(false)获取。

成员函数:

public:
    exception(string what);
    ~exception() noexcept override=default;
    //覆盖了父类的what函数,用于打印异常信息
    const char* what() const noexcept override
    {
        return m_message.data();
    }
    //覆盖了父类的stackTree函数,用于打印栈信息
    const char* stackTree() const noexcept
    {
        return m_stack.data();
    }

noexcept是告诉编译器函数中不会发生异常,这有利于编译器对程序做更多的优化。

测试:

#include "base/currentthread.h"
#include "base/exception.h"
#include <stdio.h>

void foo()
{
    throw mymuduo::exception("errorinfo");
}

int main()
{
  try
  {
    foo();
  }
  catch (const mymuduo::exception& ex)
  {
    printf("reason: %s\n", ex.what());
    printf("stack trace:\n%s\n", ex.stackTree());
  }
}

打印信息如下:

reason: errorinfo
stack trace:
/home/zqc/c_c++Repo/Qtcode/build-mymuduo-Desktop_Qt_5_14_2_GCC_64bit-Debug/mymuduo() [0x40178c]
/home/zqc/c_c++Repo/Qtcode/build-mymuduo-Desktop_Qt_5_14_2_GCC_64bit-Debug/mymuduo() [0x401da7]
/home/zqc/c_c++Repo/Qtcode/build-mymuduo-Desktop_Qt_5_14_2_GCC_64bit-Debug/mymuduo() [0x401e1c]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7fb5c75ce840]
/home/zqc/c_c++Repo/Qtcode/build-mymuduo-Desktop_Qt_5_14_2_GCC_64bit-Debug/mymuduo() [0x401249]

 

posted @ 2020-08-22 22:47  WoodInEast  阅读(139)  评论(0编辑  收藏  举报