← Back to Question List
C++ Quiz #151
Handler Order for Three Levels
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>45class AppError : public std::runtime_error {6public:7 using std::runtime_error::runtime_error;8};910class DbError : public AppError {11public:12 using AppError::AppError;13};1415void 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}2728int 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}