Consider the following C++ program. What will it print when run?
#include <iostream> #include <stdexcept> int main() { try { throw std::runtime_error("Error happened"); std::cout << "No error" << std::endl; } catch (const std::runtime_error& e) { std::cout << "Caught: " << e.what() << std::endl; } return 0; }
Remember that throwing an exception transfers control to the matching catch block.
The throw statement raises an exception. The try block stops executing at the throw, so "No error" is never printed. The catch block catches the std::runtime_error and prints its message.
What happens when this C++ code runs?
#include <iostream> #include <string> void f() { throw 42; } int main() { try { f(); } catch (const std::string& e) { std::cout << "Caught string: " << e << std::endl; } return 0; }
Check if the catch block matches the thrown exception type.
The function f() throws an int (42). The catch block tries to catch a std::string, which does not match. Since no matching catch block exists, the program terminates with an uncaught exception.
Identify the reason the exception is not caught in this C++ code snippet.
#include <iostream> #include <stdexcept> int main() { try { throw "Error"; } catch (const std::exception& e) { std::cout << "Caught exception: " << e.what() << std::endl; } return 0; }
Think about the type of the thrown object and the catch parameter type.
The code throws a string literal (type const char*). The catch block tries to catch a const std::exception&. These types do not match, so the catch block will not catch the thrown exception. This is a logical error but compiles. However, if the code tries to call e.what() on a non-std::exception, it would be invalid. Here, the catch block will not catch the thrown exception, so the program terminates.
What will this C++ program print?
#include <iostream> #include <stdexcept> int main() { try { try { throw std::logic_error("Logic error"); } catch (const std::logic_error& e) { std::cout << "Inner catch: " << e.what() << std::endl; throw; // rethrow } } catch (const std::exception& e) { std::cout << "Outer catch: " << e.what() << std::endl; } return 0; }
Remember that throw; rethrows the current exception to the outer catch block.
The inner catch block catches the std::logic_error and prints its message. Then it rethrows the same exception. The outer catch block catches it again and prints the message. So both messages appear.
Consider throwing a derived class exception object but catching by value as a base class. What happens?
Think about what happens when an object is copied by value from a derived to a base class type.
When catching exceptions by value as a base class, the derived class part is sliced off. This means the catch block only sees the base class part, losing any extra data or behavior from the derived class. This is why catching exceptions by reference is recommended.