7.3) Custom Exception Classes

In C++, you can create your own custom exception classes by deriving them from the standard exception class provided by the C++ Standard Library. This allows you to define more specific exception types that provide additional information about the nature of the error.

Custom exception classes are useful when you want to differentiate between different types of errors in your code.

Example of custom exception class

#include <iostream>
#include <exception> // Include the standard exception header

// Custom exception class derived from std::exception
class MyException : public std::exception {
public:
    MyException(const char* message) : message(message) {}

    // Override the what() function to provide error description
    const char* what() const noexcept override {
        return message;
    }

private:
    const char* message;
};

// A function that simulates an error and throws a custom exception
void simulateError() {
    throw MyException("This is a custom exception");
}

int main() {
    try {
        simulateError();
    } catch (const MyException& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }

    return 0;
}

Explanation of the code

  • We include the <exception> header to have access to the standard std::exception class.
  • We create a custom exception class MyException that derives from std::exception. It has a constructor that takes a message as a parameter and stores it as a private member.
  • We override the what() function from std::exception to provide a custom error message when the what() function is called on an instance of MyException.
  • The simulateError() function throws an instance of MyException with a custom error message.
  • In the main function, we call simulateError() inside a try block. If an exception of type MyException is thrown, it is caught by the corresponding catch block, and the custom error message is printed using the what() function.

Output of the code:

Caught exception: This is a custom exception

In this example, the custom exception class MyException is used to provide more specific information about the error. This can be particularly helpful when dealing with different types of errors in a complex program, as it allows you to handle them more precisely and provide meaningful error messages to users or developers.