Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will C++ throw with no arguments work inside another frame to rethrow an exception?

If I have a code like the following:

try {
  doSomething();
} catch (...) {
  noteError();
}

void noteError() {
  try {
    throw;
  } catch (std::exception &err) {
    std::cerr << "Note known error here: " << err.what();
  } catch (...) {
    std::cerr << "Note unknown error here.";
  }
  throw;
}

Will the original exceptions get thrown from both places inside the lower frame of noteError()?

like image 796
WilliamKF Avatar asked Aug 24 '10 22:08

WilliamKF


1 Answers

Your original code was fine. You caught different exception types and called a function that would log a message and rethrow. The throw statement is not required to appear directly inside the corresponding catch block. If you call one of those "note" functions and you're not currently handling an exception, though, then your program will call terminate().

Your new code is also fine. It's OK to catch everything and then call another function that rethrows to go to a more specific handler. That's the exception dispatcher idiom described in the C++ FAQ. It looks a little peculiar to rethrow the exception after the dispatching block has finished, but if that same throw statement had occurred after noteError returned (inside the original catch block) instead of where it is now, then it would be perfectly ordinary; it's demonstrated in the standard, §15.1/6.

like image 158
Rob Kennedy Avatar answered Oct 14 '22 09:10

Rob Kennedy