Question 5
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <stdexcept>
struct NotFound : std::runtime_error { using std::runtime_error::runtime_error; };
void relay(bool plain) {
try { throw NotFound("user 7"); }
catch (const std::exception& e) {
if (plain) throw; // original object
throw e; // copy of the static type: std::exception
}
}
int main() {
for (bool plain : {true, false}) {
try { relay(plain); }
catch (const NotFound& e) { std::cout << "NotFound:" << e.what() << ' '; }
catch (const std::exception&) { std::cout << "std::exception "; }
}
std::cout << '\n';
return 0;
}
- A NotFound:user 7 std::exception Correct
- B NotFound:user 7 NotFound:user 7
- C std::exception std::exception
- D std::exception NotFound:user 7
Correct Answer: Option A
throw e; creates a new exception of type std::exception (the static type of e), so the NotFound handler no longer matches.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!