Search code examples
c++stringexceptionprepend

Automatically add prefix to custom exception


I'm quite iffy when it comes to C++ std:exception handling. Here's some sample code I found on the web, which I currently use.

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;
};

Now, what I'd like to do is to automatically prepend every exceptions raised with the following scheme.

Some code raises a MyDerivedException exception with the following: "original_exception_message"

When the MyDerivedException receives "original_exception_message", I'd like to prepend it with: "Derived Exception Raised: "

And when MyBaseException receives the MyDerivedException exception, I'd like to prepend it with: "Base Exception Raised: "

Such that the final message would look like this:

"Base Exception Raised: Derived Exception Raised: original_exception_message"

I gotta feeling I'm going to get all sorts of nasty replies on this, about bad concepts and bad practices... But I don't claim to be an expert.

Note that the prepend messages aren't actually that. They would be a little more informative.

Thanks in advance.


Solution

  • #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;
    }
    

    And read this link http://en.cppreference.com/w/cpp/error/exception