Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 701
ThermoX Avatar asked Mar 02 '26 20:03

ThermoX


1 Answers

#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

like image 172
mooncheese Avatar answered Mar 04 '26 11:03

mooncheese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!