Complete the code to throw an exception of type int.
#include <iostream> int main() { try { throw [1]; } catch (int e) { std::cout << "Caught exception: " << e << std::endl; } return 0; }
The throw statement throws an exception. Here, 5 is an int, matching the catch (int e) block.
Complete the code to catch exceptions of type std::string.
#include <iostream> #include <string> int main() { try { throw std::string("error"); } catch ([1] e) { std::cout << "Caught string exception: " << e << std::endl; } return 0; }
std::string.The catch block must match the thrown exception type. Here, std::string& catches the thrown std::string by reference.
Fix the error in the catch block to properly catch any exception.
#include <iostream> int main() { try { throw 1.23; } catch ([1]) { std::cout << "Caught an exception" << std::endl; } return 0; }
The catch(...) block catches any exception regardless of type.
Fill both blanks to throw and catch a const char* exception.
#include <iostream> int main() { try { throw [1]; } catch ([2] e) { std::cout << "Caught message: " << e << std::endl; } return 0; }
std::string.The thrown exception is a string literal which is of type const char*. The catch block must match this type.
Fill all three blanks to create a map of exception types to messages using a lambda.
#include <iostream> #include <map> #include <string> int main() { std::map<std::string, std::string> errorMessages = { {"int", "Integer error"}, {"double", "Double error"}, {"string", "String error"} }; auto getMessage = [&](const std::string& type) -> std::string { if (errorMessages.find([1]) != errorMessages.end()) { return errorMessages[[2]]; } else { return [3]; } }; std::cout << getMessage("int") << std::endl; std::cout << getMessage("bool") << std::endl; return 0; }
The lambda checks if the type exists in the map. If yes, it returns the corresponding message; otherwise, it returns "Unknown error".