CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #116

A Custom Exception With a Fixed Message

mediumExceptions

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <exception>
3 
4class EmptyCartError : public std::exception {
5public:
6 const char* what() const noexcept override {
7 return "the cart is empty";
8 }
9};
10 
11void checkout(int items) {
12 if (items == 0) {
13 throw EmptyCartError();
14 }
15 std::cout << "charged for " << items << " item(s)\n";
16}
17 
18int 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}

🎯 Your Answer