// FactorialThrow - the factorial function which throws // an object containing more infomation // than a single string #include #include #include // Exception - generic exception handling class class Exception { public: // construct an exception object with a description // of the problem along with the file and line # // where the problem occurred Exception(char* pMsg, char* pFile, int nLine) { this->pMsg = new char[strlen(pMsg) + 1]; strcpy(this->pMsg, pMsg); strncpy(file, pFile, sizeof file); file[sizeof file - 1] = '\0'; lineNum = nLine; } // display - output the contents of the // current object to the output stream virtual void display(ostream& out) { out << "Error <" << pMsg << ">\n"; out << "Occured on line #" << lineNum << ", file " << file << endl; } protected: // error message char* pMsg; // file name and line number where error occurred char file[80]; int lineNum; }; // factorial - calculate the factorial of nBase which // is equal to nBase * (nBase - 1) * // (nBase - 2) * ... int factorial(int nBase) { // if nBase < 0... if (nBase <= 0) { // ...throw an error throw Exception("Negative argument to factorial", __FILE__, __LINE__); } // begin with an "accumulator" of 1 int nFactorial = 1; // loop from nBase down to one, each time // multiplying the previous accumulator value // by the result do { nFactorial *= nBase; } while (--nBase > 1); // return the result return nFactorial; } int main(int nArgc, char* pszArgs[]) { // call factorial in a loop. Catch any exceptions // that the function might generate try { for (int i = 6; ; i--) { cout << "factorial(" << i << ") = " << factorial(i) << "\n"; } } // catch an Exception object catch(Exception x) { // use the built-in display member function // to display the object contents to the // error stream x.display(cerr); } return 0; }