自动为自定义例外添加前缀
Automatically add prefix to custom exception
当涉及到C++std:异常处理时,我非常生气。 这是我在网络上找到的一些示例代码,我目前正在使用。
class MyBaseException : public std::exception
{
public:
explicit MyBaseException(const std::string & message)
: m_Base(message.c_cstr()) {}
explicit MyBaseException(const char *message)
: m_Base(message) {}
virtual ~MyBaseException() throw () {}
protected:
typedef std::exception m_Base;
};
class MyDerivedException : public MyBaseException
{
public:
explicit MyDerivedException (const std::string & message)
: m_Base(message.c_cstr()) {}
explicit MyDerivedException (const char *message)
: m_Base(message) {}
virtual ~MyDerivedException () throw () {}
protected:
typedef MyBaseException m_Base;
};
现在,我想做的是自动在使用以下方案引发的每个异常之前添加前缀。
某些代码会引发 MyDerivedException 异常,如下所示:"original_exception_message"
当MyDerivedException收到"original_exception_message"时,我想在它前面加上:"引发的派生异常:"
当MyBaseException收到MyDerivedException异常时,我想在它前面加上:"引发的基本异常:"
这样,最终消息将如下所示:
"引发的基本异常:引发的派生异常:original_exception_message"
我得觉得我会得到各种关于这个的讨厌的回复,关于糟糕的概念和不良做法......但我不声称自己是专家。
请注意,前置消息实际上并非如此。它们会提供更多的信息。
提前谢谢。
#include <iostream>
#include <exception>
class MyBaseException : public std::exception
{
public:
explicit MyBaseException(const std::string & message)
: m_message("Base Exception Raised: " + message) {}
virtual const char* what() const throw ()
{
return m_message.c_str();
}
private:
const std::string m_message;
};
class MyDerivedException : public MyBaseException
{
public:
explicit MyDerivedException (const std::string& message)
: MyBaseException("Derived Exception Raised: " + message) {}
};
int main()
{
try
{
throw MyDerivedException("derived");
}
catch(std::exception const& e)
{
std::cout << e.what();
}
return 0;
}
并阅读此链接 http://en.cppreference.com/w/cpp/error/exception
相关文章:
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 定义宏以将前缀 0x 添加到十六进制字符串文本
- 如何在自定义对象的<<运算符中添加自定义前缀
- 代码 C++ 以添加前缀关键字以使其有效
- 宏,用于定义带有添加前缀的新宏
- 为局部变量名称添加前缀的"nicer"替代方法?
- 在指向另一个宏的可变参数宏中为每个参数添加前缀
- 将错误处理添加到加载数据的函数(但有时还需要使用默认值)
- 为什么非犯罪序列化添加了5个字节零前缀
- 如何将文件添加到Android项目中,然后使用NDK加载它
- 将 "Qt5Widgets" 的安装前缀添加到CMAKE_PREFIX_PATH
- 如何为宏符号添加前缀
- 是否可以将 dll 添加到资源,并使用 LoadLibrary 从资源加载该 dll?C++
- gdb:在0x2aaaaaaab000添加的符号文件系统提供的 DSO 中找不到可加载的部分
- 如何让 gcc 为所有符号名称添加前缀
- cmake为链接器添加前缀
- 在C++命名空间中,当在头中声明的非成员子例程前面加前缀时,“static”限定符是否有任何作用
- 如何在加载数据库时在QTableView中添加QPushButton
- 在c++中为char*添加char前缀的最佳方法
- 构建cpp-netlib失败-未添加lib前缀