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

Handler Order for Three Levels

mediumExceptions

DbError derives from AppError, which derives from std::runtime_error. Which handler order lets every exception reach the MOST specific handler that fits it?

📄 Code

1#include <iostream>
2#include <stdexcept>
3#include <string>
4 
5class AppError : public std::runtime_error {
6public:
7 using std::runtime_error::runtime_error;
8};
9 
10class DbError : public AppError {
11public:
12 using AppError::AppError;
13};
14 
15void run(int step) {
16 if (step == 1) {
17 throw DbError("connection lost");
18 }
19 if (step == 2) {
20 throw AppError("bad setting");
21 }
22 if (step == 3) {
23 throw std::runtime_error("disk full");
24 }
25 std::cout << "step " << step << " ok\n";
26}
27 
28int main() {
29 for (int step = 1; step <= 4; step++) {
30 try {
31 run(step);
32 } catch (const DbError& e) {
33 std::cout << "db: " << e.what() << "\n";
34 } catch (const AppError& e) {
35 std::cout << "app: " << e.what() << "\n";
36 } catch (const std::exception& e) {
37 std::cout << "std: " << e.what() << "\n";
38 }
39 }
40 return 0;
41}