c++ How in runtime to give the user a suitable exception by the error code?

I need to create some interface which will able to give me suitable exception by code(int).
Exception Inheritance:

BaseException : public std::exception {...};
DerivedException1 : public BaseException {...};
DerivedException2 : public BaseException {...};

I need a function like get(int code) to solve this problem:

try {
    int code = foo();
    throw get(code);
} 
catch(DerivedException1& e) {...}
catch(DerivedException2& e) {...}
catch(BaseException& e) {...}

Thank you all in advance!

Upvotes: 2

Views: 68

Answers (1)

Jarod42
Jarod42

Reputation: 217135

throw throws by value, so you have slicing with:

std::exception& e = /*...*/;
throw e; // throws a std::exception, not possible derived class

Then you might do something like:

void as_exception(int error_code)
{
    switch (error_code)
    {
        case 0: return; // Not an error.
        case 1: throw DerivedException1();
        case 2: throw DerivedException2();
        // ...
    }
}

With usage similar to:

try {
    const int code = foo();
    as_exception(code);
} 
catch (const DerivedException1& e) {...}
catch (const DerivedException2& e) {...}
catch (const BaseException& e) {...}

Similarly, you might use std::exception_ptr the following way:

std::exception_ptr as_exception_ptr(int error_code)
{
    switch (error_code)
    {
        case 0: return nullptr; // Not an error.
        case 1: return std::make_exception_ptr(DerivedException1());
        case 2: return std::make_exception_ptr(DerivedException2());
        // ...
    }
}

With usage similar to:

try {
    const int code = foo();
    const auto eptr = as_exception_ptr(code);
    if (eptr) {
        std::rethrow_exception(eptr);
    }
} 
catch (const DerivedException1& e) {...}
catch (const DerivedException2& e) {...}
catch (const BaseException& e) {...}

Upvotes: 4

Related Questions