Just fumbling around with exceptions for no further reason. In C++20, I noticed a behaviour around the std::rethrow_exception
function when used with nested exceptions and std::current_exception
.
Consider this example:
#include <iostream>
#include <exception>
using namespace std;
int main()
{
struct B {
B(int ii): i(ii) { }
virtual ~B() { }
int i;
};
try {
try {
throw B(1);
}
catch (const B &b) {
std::throw_with_nested(B(2));
}
}
catch (const B &b) {
cout << "B" << b.i << endl;
try {
std::rethrow_if_nested(b); // works
//std::rethrow_if_nested(std::current_exception()); // doesn't work
}
catch (const B &b2) {
cout << "B" << b2.i << endl;
}
}
}
If I rethrow the exception b
itself, I get the following output:
B2
B1
This is what I expected. The outer catch
block gets the outer exception, then rethrows it so that the second catch
block gets the inner/nested exception.
However, when I change the commented lines, I suddenly only get B2
and the inner/nested exception seems to be lost. This also happens e.g., when the exception is captured in an std::exception_ptr
midway.
How is that?