CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #155

An Exception Crosses Three Functions

hardExceptions

main calls level1, which calls level2, which calls level3, and level3 throws. There is no handler in any of the three functions. What is printed?

📄 Code

1#include <iostream>
2#include <stdexcept>
3 
4void level3(int n) {
5 std::cout << "enter 3\n";
6 if (n > 2) {
7 throw std::runtime_error("deep failure");
8 }
9 std::cout << "leave 3\n";
10}
11 
12void level2(int n) {
13 std::cout << "enter 2\n";
14 level3(n);
15 std::cout << "leave 2\n";
16}
17 
18void level1(int n) {
19 std::cout << "enter 1\n";
20 level2(n);
21 std::cout << "leave 1\n";
22}
23 
24int main() {
25 try {
26 level1(5);
27 } catch (const std::exception& e) {
28 std::cout << "caught in main: " << e.what() << "\n";
29 }
30 return 0;
31}