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
Post a Comment