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

template<typename E>
void rethrow_unwrapped(const E& e)
{
    try {
        std::rethrow_if_nested(e);
    } catch(const std::nested_exception& e) {
        rethrow_unwrapped(e);
    } catch(...) {
        throw;
    }
}

void foo();

int main()
{
    try {
        foo();
    } catch(const std::exception& e) {
        try {
            rethrow_unwrapped(e);
        } catch (const std::logic_error& e) {
            std::cout << "success! unwrapped to logic_error" << std::endl;
        }
    }

    return 0;
}

void never_called()
{
    throw std::logic_error("never_called() was called");
}

void throws_with_nested()
{
    try {
        never_called();
    } catch (...) {
        std::throw_with_nested( std::runtime_error("something broke") );
    }
}

void foo()
{
    try {
        throws_with_nested();
    } catch (...) {
        std::throw_with_nested( std::runtime_error("oops") );
    }
}