CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #132

Why Catch by const Reference

easyExceptions

The handler is written as catch (const std::exception& e). Why a const reference rather than catch (std::exception e)?

📄 Code

1#include <iostream>
2#include <stdexcept>
3 
4void load(int size) {
5 if (size <= 0) {
6 throw std::runtime_error("size must be positive");
7 }
8 std::cout << "loaded " << size << "\n";
9}
10 
11int main() {
12 try {
13 load(3);
14 load(0);
15 } catch (const std::exception& e) {
16 std::cout << "caught: " << e.what() << "\n";
17 }
18 return 0;
19}