HiveBrain v1.2.0
Get Started
← Back to all entries
debugcppMinor

How to chain exceptions?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
chainexceptionshow

Problem

I have some function like:

void foo() { ... }

int main() {
  ...
  try {
    ...
    foo();
    ...
  } catch (const std::exception &e) {
    std::cout << "Fatal error: e.what() << 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 &e) {
    std::cout << "Fatal error: " << e.what() << std::endl;
    return;
  }

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

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


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

void foo()
{
  try {
    ..
  } catch (const std::exception &) {
    std::cout << "Foo failed. The reason is:" << 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?

Solution

You can re-throw an exception:

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

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

Code Snippets

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

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

Context

StackExchange Code Review Q#42767, answer score: 7

Revisions (0)

No revisions yet.