Complete the code to catch an integer exception.
#include <iostream> int main() { try { throw 10; } catch ([1]) { std::cout << "Caught an integer exception." << std::endl; } return 0; }
The catch block must specify the type of exception it handles. Here, int e catches integer exceptions.
Complete the code to catch a standard exception by reference.
#include <iostream> #include <exception> #include <stdexcept> int main() { try { throw std::runtime_error("Error occurred"); } catch (const [1]& e) { std::cout << "Caught exception: " << e.what() << std::endl; } return 0; }
Standard exceptions are caught by reference to std::exception or its derived classes.
Fix the error in the catch block to properly catch a double exception.
#include <iostream> int main() { try { throw 3.14; } catch ([1]) { std::cout << "Caught a double exception." << std::endl; } return 0; }
int e or float e to catch a double exception.The thrown value is a double, so the catch block must specify double e to catch it correctly.
Fill both blanks to catch exceptions of type int and std::string separately.
#include <iostream> #include <string> int main() { try { throw [1]; } catch ([2] e) { std::cout << "Caught int exception: " << e << std::endl; } catch (std::string e) { std::cout << "Caught string exception: " << e << std::endl; } return 0; }
The thrown exception is an integer 10, so the first catch must handle int type.
Fill all three blanks to catch exceptions of type float, int, and std::exception.
#include <iostream> #include <exception> int main() { try { throw [1]; } catch ([2] e) { std::cout << "Caught float exception: " << e << std::endl; } catch ([3] e) { std::cout << "Caught int exception: " << e << std::endl; } catch (const std::exception& e) { std::cout << "Caught std::exception: " << e.what() << std::endl; } return 0; }
The thrown exception is a float literal 3.14f, so the first catch handles float. The second catch handles int exceptions.