自动为自定义例外添加前缀

Automatically add prefix to custom exception

本文关键字:添加 加前缀 自定义      更新时间:2023-10-16

当涉及到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