My Pensieve

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

All about exceptions

Exception handling in C++

Below is an example of exceptions with polymorphism. Throw throws an object of a class( can be derived from std::exception).what is an operator of this class that returns a const char* .We can use polymorphism to implement a single catch that has an argument as reference to base class. We use multiple derived classes to throw different errors.

#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