A User Defined Exception is an Exception designed by the system engineers to occur during runtime to reflect aberrant conditions that arise during execution, often preventing other more generic runtime conditions such as Overflow, Wrap Around, Underflow, Division by Zero (DIV/0) etc. The User Defined Exceptions typically provide specific diagnostic messages to help during later forensic analysis of logs. In the following example, interests are checked until n interest rate greater than 20%, and when they are, the Usury exception is raised.
#include <iostream> #include <exception> using namespace std; class Usury : public exception { int _interestRate; public : const char* explaination() { return "Usury Interest Rate detected"; } // End explaination }; // End Exception Usury int main() { float interestRate = 0; try { while(1) { interestRate+=interestRate+.5; if ( interestRate >= 20.0 ) { Usury usery; throw usery; } // End interestRate usery check cout << "Interest Rate: " << interestRate <<endl; } // End while loop } // End try block catch ( Usury _usuryException ) { cout interestRate << " interest "<< ex.explaination(); } // End catch block return 0; } // End main routine
When these occur, the system catches the error and a User Defined Exception is raised.
Deciding whether to use an User Defined Exception to or a return values for Control Flow is a balance of several “forces”: