Search code examples
c++optimizationexceptiontry-catchthrow

How to avoid writing repeated code in catch blocks?


I am using QT 4.8 (C++) for desktop application project, and writing exception handling which is as follows :

void callerMethod()
{
  try
  {
   method1();
  }
  catch(Exception1& e)
  {
    // display critcal error message
    // abort application
  }
  catch(std::Exception& e)
  {
   // print exception error message
  }
  catch(...)
  {
   // print unknown exception message
  } 
}

void method1()
{
  try
  {
   // some initializations
   // some operations (here exceptions can occur)
   // clean-up code (for successful operation i.e no exception occurred)
  }
  catch(Exception1& e)
  {
   // clean-up code
   throw e;
  }
  catch(Exception2& e)
  {
   // clean-up code
   throw e;
  }
  catch(Exception3& e)
  {
   // clean-up code
   throw e;
  }
  catch(...)
  {
   // clean-up code
   throw;
  }
}

So my question do I need to write the clean-up code in every catch block? Is there any way I can avoid writing repeated code?

NOTE:: [ In method1() ] I want to re-throw exceptions which occurred to my caller.So I can not catch them in single catch block, because then type information will be lost.


Solution

  • Method1 can be much simplified by two concepts:

    1. RAII. Put any clean-up code into destructors, and the clean-up code will be centralized.
    2. Use the unqualified throw, and you won't need to know about the type of exception thrown.

    So, method1() should look like:

    void method1()
    {
         // some initializations of RAII objects
         // some operations (here exceptions can occur)
    }
    

    The first catch clause in callerMethod can be removed if you derive Exception1 from std::exception, since the what() method is virtual.