← Back to Question List
C++ Code Walkthrough #117
A Custom Exception Built at Run Time
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <stdexcept>3#include <string>45class UnknownCommand : public std::runtime_error {6public:7 explicit UnknownCommand(const std::string& name)8 : std::runtime_error("unknown command: " + name) {}9};1011void run(const std::string& command) {12 if (command != "start" && command != "stop") {13 throw UnknownCommand(command);14 }15 std::cout << "running " << command << "\n";16}1718int main() {19 std::string commands[] = {"start", "jump", "stop", "fly"};20 for (const std::string& command : commands) {21 try {22 run(command);23 } catch (const std::runtime_error& e) {24 std::cout << e.what() << "\n";25 }26 }27 return 0;28}