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.
Table of Contents
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 standardstd::exception
class. - We create a custom exception class
MyException
that derives fromstd::exception
. It has a constructor that takes a message as a parameter and stores it as a private member. - We override the
what()
function fromstd::exception
to provide a custom error message when thewhat()
function is called on an instance ofMyException
. - The
simulateError()
function throws an instance ofMyException
with a custom error message. - In the
main
function, we callsimulateError()
inside atry
block. If an exception of typeMyException
is thrown, it is caught by the correspondingcatch
block, and the custom error message is printed using thewhat()
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.