Search code examples
c++exceptionrethrow

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()?


Solution

  • The wording in the standard (§15.1/2) is (emphasis mine):

    When an exception is thrown, control is transferred to the nearest handler with a matching type (15.3); “nearest” means the handler for which the compound-statement, ctor-initializer, or function-body following the try keyword was most recently entered by the thread of control and not yet exited.

    When has a try block "exited"? According to the grammar (§15/1), try blocks end with a sequence of handlers, so the block ends when the last handler ends. In other words:

    try // <- start of try block
    {
    }
    catch (whatever) // <- first handler
    {
    }
    // ... more handlers
    catch (whatever_again) // <- last handler
    {
    } // <- end of try block
    

    So yes, your code is fine. When re-thrown, the nearest try block has a matching handler (namely catch (...)), so that handler is entered.