Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to re-throw an abstract class error from a catch block

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;
      |               ^

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading