I would like to create a hierarchy of exceptions. I used the C++ idiom “Polymorphic Exception”.
The difficult bit is that I would like those classes to derive from std::exception – to be able to catch any exception at any point of the code with a try … catch(exception &e).
However, I want to handle exceptions differently whether the exception comes from std::exception or from my user-defined exceptions.
This would suggest to use polymorphism, however I cannot define a virtual function on std::exception.
I also tried with function templates (see code below), but it doesn’t work because the template function called is determined at compile time.
#include <iostream>
#include <string>
using namespace std;
#include <boost\type_traits\is_base_of.hpp>
#include <boost\utility\enable_if.hpp>
class BaseError :public exception {
public:
virtual void raise(){throw *this;}
virtual string msg (){ return "This is the base class"; }
};
class DerivedError: public BaseError {
public:
void raise(){throw *this;}
string msg (){ return "This is the derived class"; }
};
template <typename T>
typename boost::disable_if<boost::is_base_of<BaseError, T>>::type
handleException(T &e)
{
cout << "Handling generic exception" << endl;
cout << e.what() << endl;
}
template <typename T>
typename boost::enable_if<boost::is_base_of<BaseError, T>>::type
handleException(T &e)
{
cout << "Handling specific exception" << endl;
cout << e.msg() << endl;
}
int main () {
BaseError b;
handleException(b);
// prints "Handling specific exception"
// prints "This is the base class"
try{
throw exception("Exception !!!");
}
catch (exception &e){
handleException(e);
// prints "Handling generic exception"
// prints "Exception !!!"
}
try{
BaseError b;
b.raise();
}
catch (exception &e){
handleException(e);
// prints "Handling generic exception" - I would like the specific behaviour
// prints "Unknown exception"
}
try{
DerivedError d;
d.raise();
}
catch (exception &e)
{
handleException(e);
// prints "Handling generic exception" - I would like the specific behaviour
// prints "Unknown exception"
}
return 0;
}
Any idea of how to achieve this?
Thanks in advance!
You can rethrow an exception at any point, it will be defined if it happens between a catch. For instance:
Now the nested
try-catchblock could be anywhere, it could be a function or even an object destructor. You can compose a set of objects that handle a particular exception, chain them together and callthrow;at the end of the chain. Pseudo code:Then the above example can be construed like this:
The same hierarchy can be created manually, using inheritance and regular classes, where you define each of the exception levels and how to handle them.