Mark As Completed Discussion

Let's go through a practical coding example using custom exceptions related to our reader's interest in AI finance. Imagine we have an AI strategy in place for predicting market patterns, and we have an acceptable performance threshold of 80%. If the performance of the current AI model falls below this threshold, we want to throw a Strategy (Strat) Error.

Here's how we'd set that up in C++:

First, we create a StratError class, derived from std::exception and override the what method to print out a helpful error message.

In the main function, we simulate the performance of our current AI model with a variable modelPerformance. We set a try block that checks if the performance is below the threshold, in which case it throws a StratError. The catch block catches this and uses cerr to output our custom error message. This example showcases how you can create specific exceptions for certain use-cases and handle them accordingly.

Please note that std::cerr is used instead of the usual std::cout for error messages. Like cout, cerr also writes to the standard output. However, cerr is unbuffered, and is typically used for error output. You will thus immediately see error messages, which is beneficial and often essential for debugging.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment