All My Brain Where stuff from my brain lands

May 12, 2009

Extending std::exception

Filed under: Programming — Tags: , , , — Dennis @ 4:06 pm

So you’re writing some C++ code, feeling all object oriented and all, and you decide you’d like an application specific exception whenever one of your methods has an issue. You’d like to have error messages that the exception can print up if thrown and you think to yourself, “hey, I’ll just extend std::exception, add the error string, and be on my way.”

Problem: So here is the puzzle. What is wrong with this code:

using namespace std;
class my_error : public exception {
   string m_err;
    my_error ( const string &err) : m_err(err) {}
    const char* what() { return m_err.c_str(); }

Think about it for a bit before scrolling down more. Take a look at the header definition for exception.

Ok, ready to move on? Did you find the problem?


The standard exception does not declare it’s copy constructor virtual.

 exception& operator= (const exception&) throw();

This is in part because in order to provide exception safe c++, the exception class can’t throw exceptions itself. This is the same reason using strings member variables is discouraged for exceptions. Their constructors can also throw exceptions. Anyway, the result is that if client code catches std::exception, copies the exception, and prints it, m_str hasn’t been copied and you get garbage or errors. Not what was expected was it.


This whole problem was loaded just slightly. There is already a standard exception that can take a string message as an argument.

class my_exc : public runtime_error {
  my_exc ( const string &err ) : runtime_error (err ) {}
  // there, you can add more methods here.
  // remember, you can't add data members any more here
  // than you can add them to exception derived classes though.

Get it? Got it? Good.

Powered by WordPress

%d bloggers like this: