My understanding about exception handling is very limited. While I find it is easy to throw an exception (or I can pack it using expected<T>
for later consumption), I have very little idea about what to do with an exception.
Presently my knowledge is limited to
clean my own resources and rethrow the exception to be handled at appropriate location. e.g.
ptr p = alloc.allocate(n); try { uninitialized_copy(first,last,p);//atomic granularity, all or none } catch(...) { alloc.deallocate(p,n); throw; }
But I guess, this can be equivalently transformed in a RAII
pattern as
alloc_guard<ptr> p{alloc.allocate(n)};
uninitialized_copy(first,last,p.get());
p.commit();
catch the exception at a top level, compose & print a nice message and exit.e.g.
int main(int argc,char** argv) { try { app_t the_app(argc,argv); the_app.run(); } catch(std::runtime_error& e) { //instead of what, I can also compose the mesage here based on locale. std::cout<<e.what()<<std::endl; } }
So, all I do is in a top level function such as main
catch the exception and print an appropriate message and close.
While implementing a library with a nice set of API using various external libraries as back end for implementation, I realized that third party library exceptions are part of my API specification, as they cross my library boundary and land in user code!
So, my library API leaked all exceptions from external libraries (and each one having their own exception hierarchy) that I was using to the user code.
This leads to my question, what all can be done when I catch any exception ?
More specifically,
- Can I translate the caught exception from external library to my own exception and throw that in a generic way (say the mapping between third party library exception hierarchy and my exception API is provided as a
mpl::map
) ? - Can I do something more useful than printing a message/call stack, say resume the function at the throw site with different input parameter (say when I get that a
file_not_found
ordisk_error
, re-run the function with a different file)? - Any other pattern which is valuable to know?
Thanks