定义一个异常基类名字叫texception
继承标准库的exception
重写exception方法
_EXCEPTION_INLINE virtual const char * __CLR_OR_THIS_CALL what() const;
重写后标准写法
const char * what()const noexcept override;
由于我的IDE版本过旧对C++11支持不完善,不支持noexcept,我就把这个删掉了。也可以把noexcept写成throw()
const char * what()const throw() override;
基类的全部代码
///HPP
#ifndef TEXCEPTION_HPP
#define TEXCEPTION_HPP
#include <exception>
#include <stdexcept>
#include <string>
namespace core
{
namespace ttexc
{
class texception : std::exception
{
protected:
texception(int _id, const char * _what_arg);
public:
const char * what()const override;
static std::string name(const std::string& _name, int _id);
public:
const int m_id;
private:
std::runtime_error m_what_arg;
};
}
}
#endif // ! TEXCEPTION_HPP
//Cpp
#include "TException.hpp"
namespace core
{
namespace ttexc
{
texception::texception(int _id, const char * _what_arg)
: m_id(_id)
, m_what_arg(_what_arg) {}
const char * texception::what() const
{
return m_what_arg.what();
}
std::string texception::name(const std::string & _name, int _id)
{
return "[tt.exception." + _name + "." + std::to_string(_id) + "] ";
}
}
}
因为最近在写SDK接口,所以我派生了一个InstanceException,命名不统一是因为上面我是为了更贴合标准库的命名风格,下面是项目里给同事要一起用的代码所以两个命名方式有点不统一,也是没有办法,有时候程序员的强迫症还是要容忍适应一下的。
///Hpp
#ifndef INSTANCEEXCEPTION_HPP
#define INSTANCEEXCEPTION_HPP
#include "TException.hpp"
namespace core
{
namespace ttexc
{
class InstanceException : public texception
{
public:
static InstanceException create(int id_, const std::string& what_arg);
private:
InstanceException(int id_, const char* what_arg);
};
}
}
#endif // !INSTANCEEXCEPTION_HPP
//Cpp
#include "InstanceException.hpp"
namespace core
{
namespace ttexc
{
InstanceException InstanceException::create(int id_, const std::string & what_arg)
{
std::string w = texception::name("instance_exception", id_) + what_arg;
return InstanceException(id_, w.c_str());
}
InstanceException::InstanceException(int id_, const char * what_arg)
: texception(id_, what_arg) {}
}
}
看看我怎么用的吧~~~
bool VTELLER_API SwitchVideoOrVoice(unsigned char _state)
{
switch (_state)
{
case 0x01:
{
break;
}
case 0x02:
{
break;
}
case 0x03:
{
break;
}
case 0x04:
{
break;
}
default:
throw InstanceException::create(101, "Instance input out of range,Input is " +
static_cast<std::ostringstream&&>(std::ostringstream() << "INput.... 0x" << std::hex << +_state).str());
break;
}
return true;
}
好了就写这么多吧,明天清明节,从上海来北京后发现江浙沪有一个小吃其他地方没有:青团。
很好吃,艾草做的,艾草过敏的人可能不能吃吧。