eckit icon indicating copy to clipboard operation
eckit copied to clipboard

Add nested exception handling to the Exception classes

Open srherbener opened this issue 1 year ago • 0 comments

Is your feature request related to a problem? Please describe.

We have some use cases where nested exception handling would be helpful. Essentially where you have access to different aspects of an object at different call tree levels, but no single level where you can see all of these aspects, it can be handy to nest the exceptions as the call tree is unwound and then report at the higher level. This helps keep the information in the error message tied together.

Describe the solution you'd like

I was thinking of something like this example:

#include <exception>
#include <iostream>
#include <stdexcept>

void handleException(const std::exception& e) {
    std::cerr << "Exception: " << e.what() << '\n';
    try {
        std::rethrow_if_nested(e);
    } catch (const std::exception& nested) {
        handleException(nested);
    } catch (...) {
        std::cerr << "Unknown nested exception\n";
    }
}

void functionThatThrows() {
    try {
        throw std::runtime_error("Initial exception");
    } catch (...) {
        std::throw_with_nested(std::runtime_error("Additional context"));
    }
}

int main() {
    try {
        functionThatThrows();
    } catch (const std::exception& e) {
        handleException(e);
    }
    return 0;
}

but I'm also open to other solutions

Describe alternatives you've considered

We've tried printing a message at the lower level and then re-throwing the exception up to a higher level, but this isn't great when you want to report different exception types at different levels.

Additional context

I'm a software engineer with JCSDA and I work on the JEDI project. I'm really trying to gauge the interest in nested exception handling in eckit and I'm okay if there really isn't much interest in this. However, I thought that it might have more widespread impact if the interest is there.

Organisation

JCSDA

srherbener avatar Nov 13 '24 19:11 srherbener