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

Catching by Value Slices the Object

hardExceptions

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <exception>
3 
4class AppError : public std::exception {
5public:
6 const char* what() const noexcept override { return "generic app error"; }
7};
8 
9class ConfigError : public AppError {
10public:
11 const char* what() const noexcept override { return "config file missing"; }
12};
13 
14int main() {
15 try {
16 throw ConfigError();
17 } catch (AppError e) {
18 std::cout << "by value: " << e.what() << "\n";
19 }
20 try {
21 throw ConfigError();
22 } catch (const AppError& e) {
23 std::cout << "by reference: " << e.what() << "\n";
24 }
25 return 0;
26}

🎯 Your Answer