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

前端 未结 7 1191
眼角桃花
眼角桃花 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:24

    I asked a very similar conceptual question, see Is re-throwing an exception legal in a nested 'try'?.

    Basically, you can move the various exception handlers to a separate function by catching all exceptions, calling the handler and rethrowing the active exception.

    void handle() {
     try {
      throw;
     } catch (std::exception& err) {
       handleException(err);
     } catch (MyException& err) {
       handleMyException(err);
     } catch (...) {
       handleException();
     }
    }
    
    try {
       return _original->abstract_two(sig2);
    } catch (...) {
       handle();
    }
    

    It scales well with more different exception kinds to differenciate. You can pack the first try .. catch(...) into macros if you like to:

    BEGIN_CATCH_HANDLER
    return _original->abstract_two(sig2);
    END_CATCH_HANDLER
    

提交回复
热议问题