Is `catch(…) { throw; }` Bad Practice in C++?

c

While I agree that catching ... without rethrowing is indeed wrong, I however believe that using constructs like this:

try
{
  // Stuff
}
catch (...)
{
  // Some cleanup
  throw;
}

Is acceptable in cases where RAII is not applicable. (Please, don't ask… not everybody in my company likes object-oriented programming and RAII is often seen as "useless school stuff"…)

My coworkers says that you should always know what exceptions are to be thrown and that you can always use constructs like:

try
{
  // Stuff
}
catch (exception_type1&)
{
  // Some cleanup
  throw;
}
catch (exception_type2&)
{
  // Some cleanup
  throw;
}
catch (exception_type3&)
{
  // Some cleanup
  throw;
}

Is there a well admited good practice regarding these situations?

Best Answer

My coworkers says that you should always know what exceptions are to be thrown [...]

Your coworker, I'd hate to say it, has obviously never worked on general-purpose libraries.

How in the world can a class like std::vector even pretend to know what the copy constructors will throw, while still guaranteeing exception safety?

If you always knew what the callee would do at compile-time, then polymorphism would be useless! Sometimes the entire goal is to abstract away what happens at a lower level, so you specifically don't want to know what's going on!

Related Topic