C++ 异常类

C++标准库提供的异常如上所示,exception是最底层的基类,可以看到很多情况下的代码:

try{
	//会抛出异常的操作
}catch(const exception& e){
    e.what();		//异常信息
    LOG(e.what());	//记录一下异常信息
}

如果标准库提供的异常不满足我们的需求,那怎么办呢?答案就是自己定义,C++可以把任意类型的对象作为抛出的异常!

#pragma once
#include <string>

class my_execption{
public:
	std::string what() const{
        return msg_;
    }    
public:
    explicit my_exception(std::string str)
        :msg_(str)
        {}
private:
	std::string msg_;
}


int main(){
    try{
        throw my_exception("this is a test")
    }catch(const my_exception& e){
        std::cout<< e.what()<<std::endl;
    }
}