← Back to Question List
C++ Quiz #132
Why Catch by const Reference
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>34void load(int size) {5 if (size <= 0) {6 throw std::runtime_error("size must be positive");7 }8 std::cout << "loaded " << size << "\n";9}1011int 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}