So far we've used the predefined exceptions provided by C++, but what if none of these standard exceptions meet your needs? In such a case, you can create your own custom exceptions. Our senior engineer who has an interest in AI and finance might want to create a custom exception if an AI model's performance drops below an acceptable threshold for a financial algorithm.
To create a custom exception in C++, you can define a new class derived from the base class std::exception
. You can override the what
method with your own error message. Here, we've created a custom exception class MyException
.
In the main
function, we use throw MyException()
to throw our custom exception. Our catch
block catches MyException
and displays your custom error message.
Custom exceptions give you much more flexibility over standard exceptions and can respond better to the unique needs of your applications, especially when different actions need to be taken for different types of exception events.
xxxxxxxxxx
```cpp
using namespace std;
// Define a custom exception
class MyException : public exception {
public:
const char * what () const throw () {
return "MyException: AI model performance below acceptable threshold.";
}
};
int main() {
try {
throw MyException();
}
catch(MyException& e) {
std::cout << e.what() << std::endl;
}
catch(std::exception& e) {
// Other errors...
}
}