I have a few exceptions that look like this
class ExceptionType1Base : public std::runtime_error {
};
class ExceptionType1Derived1 : public ExceptionType1Base {
};
class ExceptionType1Derived2 : public ExceptionType1Base {
};
And another exception type
class ExceptionType2Base : public std::runtime_error {
public:
int type;
};
class ExceptionType2Derived1 : public ExceptionType2Base {
ExceptionType2Derived1() {
type = 1;
}
};
class ExceptionType2Derived2 : public ExceptionType2Base {
ExceptionType2Derived2() {
type = 2;
}
};
I would like to convert one type of exception to another when I catch it, with something like
ExceptionType1Base convertToType1Exception(ExceptionType2Base& ex) {
if(ex.type == 1) {
return ExceptionType1Derived1();
}
return ExceptionType1Derived2();
}
Then when I catch exceptions, it would be like
try {
... some code ....
} catch (const ExceptionType2Base& ex) {
throw convertToType1Exception(ex);
}
The problem with that is I lost the derived type of the converted exception and the exception that ends up being thrown is ExceptionType1Base, any better way of handling this ? I thought of using macros for exception type converting but I'm wondering if there is a better way.