I need to perform some action inside a catch block then throw the same exception I got:
#include <string>
#include <iostream>
class AbstractError {
public:
virtual std::string toString() const = 0;
};
class SomeConcreteError : public AbstractError { public:
std::string toString() const { return "division bt 0"; }
};
class SomeOtherError : public AbstractError { public:
std::string toString() const { return "null pointer deref"; }
};
void foo(int i)
{
if (i > 2) { throw SomeConcreteError(); }
else { throw SomeOtherError(); }
}
int main(int argc, char **argv)
{
try { foo(argc); }
catch (const AbstractError &e)
{
std::cout << e.toString() << "\n"; // do some action then re-throw
// throw e; doesn't work ...
}
return 0;
}
Here is the error I get:
main.cpp:28:15: error: expression of abstract class type ‘AbstractError’ cannot be used in throw-expression
28 | throw e;
| ^
>Solution :
This would throw a copy of e:
throw e;
but it’s abstract so that can’t be done. You need to rethrow the same exception:
throw;