I am trying to write code which is passed a handler for when errors occur.
class Handler {
public: virtual void handle(std::exception const& e) = 0;
};
class DoIt {
Handler* handler;
public:
void doStuff() {
try {
methodThatMightThrow();
} catch (std::exception const& e) {
handler->handle(e);
}
}
void setHandler(Handler* h) { handler = h; }
void methodThatMightThrow();
}
Different projects will use this class with different error handling techniques.
Project 1 logs an error
class Handler1: public Handler {
void handle(std::exception const& e) override {
logError(e.what());
}
};
Project 2 propagates the exception
class Handler2: public Handler {
void handle(std::exception const& e) override {
throw e;
}
};
Both of those should work. However, Handler2
will throw a copy of the exception and lose any derived class information if the exception is a subclass of std::exception
, which it almost certainly is.
Is there a good way to rethrow the original exception, or even a copy of the same type?
Aucun commentaire:
Enregistrer un commentaire