// library code #include // MS compatible compiler 2008 doesn't implement these #if defined(_MSC_VER) namespace std { struct exception_ptr {}; void rethrow_exception(exception_ptr p); exception_ptr current_exception(); } #else // gcc #include #endif // see 18.8.5 Exception propagation #include #include class exception_wrapper_base : public std::exception { public: const std::exception_ptr m_e; exception_wrapper_base(const std::exception_ptr & e) : m_e(e) { } }; template class exception_wrapper : public exception_wrapper_base { public: T m_t; exception_wrapper(const std::exception_ptr & e, const T & t) : exception_wrapper_base(e), m_t(t) { } }; template exception_wrapper make_exception_wrapper(std::exception_ptr e, T t){ return exception_wrapper(e, t); } // example // inside of some other library class my_exception : public std::exception { }; void test_function1(){ throw my_exception(); } // inside a user application // our one special sauce to all the exceptions and // then pass them on. void test_function(){ try { test_function1(); } catch(exception_wrapper_base &ewb){ // if it's already wrapped // ... add sauce // just pass it on throw ewb; } catch(...){ std::cout << "caught other exception" << std::endl; // if it's any other exception // copy the exception pointer std::exception_ptr eptr; try { std::rethrow_exception(std::current_exception()); } catch(...) { eptr = std::current_exception(); } int t = 999; // and create a new exception_wrapper type throw make_exception_wrapper(eptr, t); } } int main(){ try { test_function(); } // to catch some of the exceptions which have been wrapped. catch(exception_wrapper_base & e){ std::cout << "caught exception_wrapper_base" << std::endl; try { std::rethrow_exception(e.m_e); } catch(my_exception & me){ std::cout << "caught my_exception" << std::endl; // e has the added on information // which me has the original information const exception_wrapper & ew = static_cast< exception_wrapper &>(e); std::cout << ew.m_t << std::endl; } catch(...){ // just skip any all other exceptions not specifically handled. } } }