← Back to Question List
C++ Quiz #142
throw e Versus a Bare throw
Both functions catch a DerivedError through a const BaseError&. One rethrows with throw e;, the other with a bare throw;. What is printed?
📄 Code
1#include <iostream>2#include <exception>34class BaseError : public std::exception {5public:6 const char* what() const noexcept override { return "base"; }7};89class DerivedError : public BaseError {10public:11 const char* what() const noexcept override { return "derived"; }12};1314void copyRethrow() {15 try {16 throw DerivedError();17 } catch (const BaseError& e) {18 throw e;19 }20}2122void bareRethrow() {23 try {24 throw DerivedError();25 } catch (const BaseError&) {26 throw;27 }28}2930int main() {31 try {32 copyRethrow();33 } catch (const BaseError& e) {34 std::cout << "copy: " << e.what() << "\n";35 }36 try {37 bareRethrow();38 } catch (const BaseError& e) {39 std::cout << "bare: " << e.what() << "\n";40 }41 return 0;42}