My Pensieve

A collection of articles on Math, cricket and a few puzzles

Learning ABOUT CONST LEVEL

Exception handling in C++

This is meant to explain the differences between low level and top level const

#include <iostream>
#include <exception>

// Base Exception class
class BaseException : public std::exception {
public:
    const char* what() const noexcept override {
        return "BaseException occurred";
    }
};

// Derived Exception classes
class DerivedException1 : public BaseException {
public:
    const char* what() const noexcept override {
        return "DerivedException1 occurred";
    }
};

class DerivedException2 : public BaseException {
public:
    const char* what() const noexcept override {
        return "DerivedException2 occurred";
    }
};

void riskyFunction(int type) {
    if (type == 1) {
        throw DerivedException1();
    } else if (type == 2) {
        throw DerivedException2();
    } else {
        throw BaseException();
    }
}

int main() {
    try {
        riskyFunction(1);  // Change the parameter to test different exceptions
    } catch (const BaseException& e) {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

Leave a comment