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 #142

throw e Versus a Bare throw

mediumExceptions

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>
3 
4class BaseError : public std::exception {
5public:
6 const char* what() const noexcept override { return "base"; }
7};
8 
9class DerivedError : public BaseError {
10public:
11 const char* what() const noexcept override { return "derived"; }
12};
13 
14void copyRethrow() {
15 try {
16 throw DerivedError();
17 } catch (const BaseError& e) {
18 throw e;
19 }
20}
21 
22void bareRethrow() {
23 try {
24 throw DerivedError();
25 } catch (const BaseError&) {
26 throw;
27 }
28}
29 
30int 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}