Use throw_with_nested and catch a nested exception

I really like std :: throw_with_nested in C ++ 11 as it emulates java printStackTrace (), but right now I'm just wondering how to catch a nested exception, like this:

void f() { try { throw SomeException(); } catch( ... ) { std::throw_with_nested( std::runtime_error( "Inside f()" ) ); } } void g() { try { f(); } catch( SomeException & e ) { // I want to catch SomeException here, not std::runtime_error, :( // do something } } 

I used to think that std :: throw_with_nested throws a new exception that is multiplied by two exceptions (std :: runtime_error and SomeException), but after reading some online tutorial, it encapsulates SomeException in std :: exception_ptr, and that’s probably why I canonot catch him.

Then I realized that I could fix it using std :: rethrow_if_nested (e), but the above case are only two levels that are easy to handle, but they think of a more general situation, for example, 10 layers, and I just don't want to write std :: rethrow_if_nested 10 times to process it.

Any suggestions would be really appreciated.

+7
c ++ c ++ 11 try-catch
source share
1 answer

Deploying a std::nested_exception is done using recursion:

 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; } } 

If use would look something like this:

 try { throws(); } catch(const std::exception& e) { try { rethrow_unwrapped(e); } catch (const SomeException& e) { // do something } } 

A demonstration of this in action can be found here .

+5
source share

All Articles