c++ - Use throw_with_nested and catch nested exception -


i std::throw_with_nested in c++11 since emulates java's printstacktrace() right curious how catch nested exception, example:

void f() {     try {         throw someexception();     } catch( ... ) {         std::throw_with_nested( std::runtime_error( "inside f()" ) );     } } void g() {     try {         f();     } catch( someexception & e ) { // want catch someexception here, not std::runtime_error, :(         //     } } 

previously, thought std::throw_with_nested generates new exception multiply derived 2 exceptions (std::runtime_error , someexception) after reading online tutorial, encapsulates someexception within std::exception_ptr , it's probabaly why canonot catch it.

then realized can fix using std::rethrow_if_nested( e ) above case 2 level easy handle thinking more general situation 10 level folded , don't want write std::rethrow_if_nested 10 times handle it.

any suggestions appreciated.

unwrapping std::nested_exception readily accomplished via 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;     } } 

where usage this:

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

a demo of in action can found here.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -