C++: Catch an Exception Thrown in a Nested Call

Bjarne-stroustrup
 

Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.

  1. Create two user-defined exceptions, U0 and U1.
  2. Have function foo call function bar twice.
  3. Have function bar call function baz.
  4. Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
  5. Function foo should catch only exception U0, not U1.

Show/describe what happens when the program is run.

First exception will be caught and message will be displayed, second will be caught by the default exception handler, which as required by the C++ Standard, will call terminate(), aborting the task, typically with an error message.

#include <iostream>
class U0 {};
class U1 {};

void baz(int i)
{
	if (!i) throw U0();
	else throw U1();
}
void bar(int i) { baz(i); }

void foo()
{
	for (int i = 0; i < 2; i++)
	{   
		try {
			bar(i);
		} catch(U0 e) {
			std::cout<< "Exception U0 caught\n";
		}
	}
}

int main() {
	foo();
	std::cout<< "Should never get here!\n";
	return 0;
}

Result:

Exception U0 caught
This application has requested the Runtime to terminate it in an unusual way.

The exact behavior for an uncaught exception is implementation-defined.

SOURCE

Content is available under GNU Free Documentation License 1.2.