views:

301

answers:

3

I often want to define new 'Exception' classes, but need to have an appropriate constructor defined because constructors aren't inherited.

class MyException : public Exception 
{ 
public:
  MyException (const UString Msg) : Exception(Msg)
  {
  };
}

Typedefs don't work for this, because they are simply aliases, not new classes. Currently, to avoid repeating this trivial boilerplate, I use a #define which does the donkeywork.

#define TEXCEPTION(T) class T : public Exception \
{ \
public:\
    T(const UString Msg) : Exception(Msg) {}; \
}

...

TEXCEPTION(MyException);

But I keep wondering if there's a better way of achieving this - maybe with templates, or some new C++0x feature

+1  A: 

You could parameterize your template class with an integer:

#include <iostream>
#include <string>

using namespace std;

enum ExceptionId {
    EXCEPTION_FOO,
    EXCEPTION_BAR
};

class Exception {
    string msg_;

public:
    Exception(const string& msg) : msg_(msg) { }
    void print() { cout << msg_ << endl; }
};

template <int T>
class TException : public Exception {
public:
    TException(const string& msg) : Exception(msg) {};
};

void
foo()
{
    throw TException<EXCEPTION_FOO>("foo");
}

void
bar()
{
    throw TException<EXCEPTION_BAR>("bar");
}

int
main(int argc, char *argv[])
{
    try {
        foo();
    } catch (TException<EXCEPTION_FOO>& e) {
        e.print();
    };

    try {
        bar();
    } catch (TException<EXCEPTION_BAR>& e) {
        e.print();
    };

    return 0;
}

Although, I don't see why you would favor this over using a single class with an internal enumeration that is set/read at runtime:

class TException {
public:
    enum Type { FOO, BAR };

    TException(Type type, const string& msg) : Exception(msg), type_(type) {}

    Type type() const { return type_; }

private:
    Type type_;
};

Then just switch on the type when you catch a TException...

Judge Maygarden
The enum list is the bit I don't like :( - Each module creates/uses it's own exception, and a central 'list' of those would be a PITA to maintain. A bit like error numbers ;-) ... Now, if I could write "template <string T>" I'd be happier. typedef TException<"FOO"> FooException;
Roddy
what about using tag types? struct Foo; typedef TException<Foo> FooException;
Johannes Schaub - litb
What's the difference between maintaining the enum list and maintaining the macro calls?
Judge Maygarden
macro calls can be spread out over many source files - no coupling. Exception types have appropriate local scope if needed. But - Enum list must be in one place to avoid duplication - I think?
Roddy
Why not derive from a standard exception. std::runtime_error. They use what()
Martin York
+3  A: 
Johannes Schaub - litb
I am not sure how this solves the original problem. The difference is the you define Ctor rather than the constructor.
Martin York
I liked this answer better without the policy/boost/stringstream stuff. Now I'm just confused :-s "In the meantime", I'll be sticking to #define.
Roddy
no, i don't. you don't have to define Ctor Martin. as you see with StackOverflowError, you can get away with just "struct StackOverflow : ExceptionDefImpl { }; typedef ExceptionT<StackOverflow> StackOverflowError; and have a string taking ctor.
Johannes Schaub - litb
i'm sorry Roddy if it confused you :/ i'll make it <sub>..</sub> so it's smaller :)
Johannes Schaub - litb
@litb: OK, I admit I enjoy being confused by your answers when I don't understand them - it makes me dig deeper and learn more!
Roddy
+1  A: 
// You could put this in a different scope so it doesn't clutter your namespaces.
template<struct S>   // Make S different for different exceptions.
class NewException :
    public Exception 
{ 
    public:
        NewException(const UString Msg) :
            Exception(Msg)
        {
        }
};

// Create some new exceptions
struct MyExceptionStruct;    typedef NewException<MyExceptionStruct> MyException;
struct YourExceptionStruct;  typedef NewException<YourExceptionStruct> YourException;
struct OurExceptionStruct;   typedef NewException<OurExceptionStruct> OurException;

// Or use a helper macro (which kinda defeats the purpose =])
#define MAKE_EXCEPTION(name) struct name##Struct; typedef NewException<name##Struct> name;

MAKE_EXCEPTION(MyException);
MAKE_EXCEPTION(YourException);
MAKE_EXCEPTION(OurException);

// Now use 'em
throw new MyException(":(");
strager
that won't work mate. string literals have internal linkage (won't be exported), and are not guaranteed to yield the same address when used multiple times. a pointer template nontype parameter, however, requires the address of an identifier with external linkage. i miss string template args too tho
Johannes Schaub - litb
@litb, Ah, I completely forgot about that issue. Do you think using std::string (or UString) would work?
strager
Nope, that won't work either.
Judge Maygarden
+1 for a nice try - thanks!
Roddy
the only way to make it work is: extern const char name[] = "MyException"; typedef NewException<name> MyException; (it won't even work within a single translation unit using the literal. teh std forbids it). maybe with some preprocessor trickery and #T trick you can do it in one line :)
Johannes Schaub - litb
Well, I've updated my answer to give it another shot. Looks kinda messy, though...
strager