How can I abstract out a repeating try catch pattern in C++

前端 未结 7 1177
眼角桃花
眼角桃花 2020-12-15 04:28

I have a pattern that repeats for several member functions that looks like this:

int myClass::abstract_one(int sig1)
{
  try {
    return _original->abstr         


        
7条回答
  •  轮回少年
    2020-12-15 05:06

    One option, if there are a limited number of function arities, would be to use a function template:

    template 
    ReturnT call_and_handle(ClassT* obj, ReturnT(ClassT::*func)()) 
    {
        try {
            return (obj->*func)();
        }
        catch (const std::exception& ex) {
            handleException(ex);
        }
        catch (...) {
            handleException();
        }
        return ReturnT();
    }
    

    This assumes that handleException is some non-member function, but it is easy to modify it if it is a member function. You need to decide what call_and_handle returns if an exception is handled; I have it returning an initialized ReturnT as a placeholder.

    This reduces your member functions to:

    int myClass::abstract_one()
    {
        return call_and_handle(_original, &myClass::abstract_one);
    }
    

    You would need a separate function template for calling functions that have one parameter, two parameters, etc.

    If you have functions that have an unwieldy number of parameters and you were really desperate, you could use a macro (I wouldn't really recommend this, though):

    #define CALL_AND_HANDLE(expr)           \
        try {                               \
            return (expr);                  \
        }                                   \
        catch (const std::exception& ex) {  \
            handleException(ex);            \
        }                                   \
        catch (...) {                       \
            handleException();              \
        }
    

    Which can be used as:

    int myClass::abstract_one()
    {
        CALL_AND_HANDLE(_original->myClass::abstract_one());
    }
    

    As an aside, if you catch (...) and do not rethrow the caught exception, you should in most cases terminate the program.

提交回复
热议问题