How to avoid re-writing code in catch blocks?

I use QT 4.8 (C ++) for a desktop application project and write exception handling that looks like this:

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 is: do I need to write cleanup code in every catch block ? Is there a way I can avoid writing duplicate code ?

NOTE :: [ In method1 () ] I want to repeat the exceptions that occurred to my caller.So I cannot catch them in one catch block, because then the type information will be lost.

+5
source share
3 answers

1 :

, method1() :

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

catch callerMethod , Exception1 std::exception, what() .

+8

. . / , ... .

( :

int main()
try
{
    function_calls_that_may_throw();
    // ...
}
catch(my_exception& e)
{
    e.do_exception_stuff();
}
catch(std::exception& e)
{
    std::cout << e.what();
}
catch(...)
{
    std::cout << "Something bad happened.\n";
}

, - .

, / , , , , .

+1

If all of your cleanup code is completely identical, you can do everything in your catch (...) block:

try {
   // code
} catch (...) {
   // cleanup
   throw;
}

If your code is slightly different, you can always call the cleanup function:

try {
   // code
} catch (exc1 ex) {
   cleanup(args);
   // exc1 specific
   throw;
} catch (exc2 ex) {
   cleanup(args);
   // exc2 specific
   throw;
} catch (...) {
   cleanup(args);
   throw;
}
0
source

All Articles