How to chain exceptions? I have some function like:

void foo() { ... }


int main() {
  ...
  try {
    ...
    foo();
    ...
  } catch (const std::exception &amp;e) {
    std::cout &lt;&lt; "Fatal error: e.what() &lt;&lt; std::endl();
    return;
  }
  ...
}


If an exception is thrown from foo, I'd like to know it. Also I want to know the reason of the original exception. I can split the code like this:

int main() {
  ... 
  try {
    ... 
  } catch (const std::exception &amp;e) {
    std::cout &lt;&lt; "Fatal error: " &lt;&lt; e.what() &lt;&lt; std::endl;
    return;
  }

  try {
    foo();
  } catch (const std::exception &amp;e) {
    std::cout &lt;&lt; "Fatal error (foo): " &lt;&lt; e.what() &lt;&lt; std::endl;
    return;
  }

  try {
    ... 
  } catch (const std::exception &amp;e) {
    std::cout &lt;&lt; "Fatal error: " &lt;&lt; e.what() &lt;&lt; std::endl;
    return;
  }
  ...
}


It doesn't look good. Instead, I can update foo:

void foo()
{
  try {
    ..
  } catch (const std::exception &amp;) {
    std::cout &lt;&lt; "Foo failed. The reason is:" &lt;&lt; std::endl;
    throw;
  }
}


However, I do not like solution, too (maybe, because error logging is split).  What is the right way to raise the exception upward?
You can re-throw an exception:

int main() {
    ...   
    try {
        ...
        try
        {
            foo();
        }
        catch(std::exception const&amp; e) {
            std::cout &lt;&lt; "Fatal error: " &lt;&lt; e.what() &lt;&lt; std::endl;

            throw; // re-throw the exception.
                   // or you could throw a different exception.
        }
        ...   
    } catch (const std::exception &amp;e) {
        std::cout &lt;&lt; "Fatal error: " &lt;&lt; e.what() &lt;&lt; std::endl;
        return;   
    }
    ... 
}