When an exception is thrown, it would be nice to be able to add information about how the error could happen, as the exception propagates up the call stack.
With information i don't mean technical info (e.g. Error in /src/foo.cpp:26
), but something in context of the domain (e.g. Failed to load image "foo.png"
).
So instead of tracing the actual call stack, i want to provide my own information.
What's the best way to implement that in c++11?
I tried using nested exceptions with std::throw_with_nested()
but the problem there is that if you want to catch some exceptions by their type only the outermost exception can be caught (I want the innermost).
Like in this example:
#include <iostream>
#include <exception>
void run()
{
try
{
throw 1;
}
catch(...)
{
std::throw_with_nested(std::runtime_error("run() failed"));
}
}
int main()
{
try {
run();
} catch(const int& e) {
// won't handle this error because only outermost exception can be caught
std::cerr << e << std::endl;
}
}
That is a problem, because the outer exceptions are only there to provid informartion, and only the innermost represents the actual error.