1

I have some "nested" try catch blocks, split across functions, but essentially it boils down, for classes Foo and Bar, to this:

try { for (;;){ try { Foo foo; try { Bar bar; if (something){ continue; } } catch (...){ std::cout << "inner"; } } catch (...){ std::cout << "middle"; } } } catch (...){ std::cout << "outer"; } 

Both classes can throw exceptions in their destructors.

If continue is reached then as the stack unwinds, and during the destruction of foo and bar, an exception is thrown, then I'm expecting to print "outer", but it doesn't do that. What is going on?

8
  • why would it print something? where are you throwing an exception? Commented Jul 6, 2015 at 13:00
  • @DavidHaim as it says "Both classes can throw exceptions in their destructors". Commented Jul 6, 2015 at 13:07
  • you don't throw an exception from a destructor. see stroustrup.com/bs_faq2.html#ctor-exceptions Commented Jul 6, 2015 at 13:08
  • Unfortunately I use a 3rd party base class that does. So needed to know which catch site the exception will go to. Commented Jul 6, 2015 at 13:11
  • "If continue is reached then as the stack unwinds, and during the destruction of foo and bar, an exception is thrown" - this shows some confusion somewhere. The stack doesn't unwind until an exception is thrown. "continue" being reached has nothing to do with stack unwinding. Commented Jul 6, 2015 at 13:11

1 Answer 1

3

The standard makes this clear:

If a destructor throws an exception then it is caught by the try block in which the variable is defined.

So if ~Bar() throws an exception, then the output is "inner". If ~Foo() throws, then the output is "middle";

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.