I currently have some code I am trying to refactor. A large set of exceptions has some common code for all exceptions as well as some specific code which needs to be handled separately for each specific exception type. I am trying to figure out how to get rid of the common part in each catch block. One Idea is to do it like this:
try {
/* Stuff that may fail */
} catch( const std::exception & ) {
/* do common part here */
try { throw; }
catch( const exception1 & ) {
/* do stuff for exception1 here */
}
catch( const exception2 & ) {
/* do stuff for exception2 here */
}
}
However this strikes me as somewhat ugly.
Is there a better way to factor out this common logic, or is there actually a reason to avoid this attempt altogether?
In general,
try/catchshould only appear sparsely in the code. The problem is that many times the actions done in acatchclause should also be done in case of early return, for example.Idiomatic C++ uses RAII extensively to avoid situation where you need to cleanup in a
catchclause, which generally removes most of the work.Now, your pattern is not so bad per se, it does factor the common stuff. But this common stuff could perhaps be handled automatically.
In all the code bases I have stumbled upon, only a few times did I see a genuine use of
catchclause, don’t use it as a clutch.