← Back to Question List
C++ Code Walkthrough #116
A Custom Exception With a Fixed Message
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <exception>34class EmptyCartError : public std::exception {5public:6 const char* what() const noexcept override {7 return "the cart is empty";8 }9};1011void checkout(int items) {12 if (items == 0) {13 throw EmptyCartError();14 }15 std::cout << "charged for " << items << " item(s)\n";16}1718int main() {19 try {20 checkout(3);21 checkout(0);22 checkout(5);23 } catch (const EmptyCartError& e) {24 std::cout << "cannot checkout: " << e.what() << "\n";25 }26 return 0;27}