Sinh viên lớp {public: / / giống như trước đây nổi cấp () {trở lại điểm trung bình;} / / ở đây chúng tôi cho phép cấp được thay đổi cấp nổi (float newGPA) {float oldGPA = điểm trung bình; / / chỉ khi giá trị mới có hiệu lực nếu Điều cần thiết là một kiểm tra để đảm bảo rằng chỉ số này nằm trong khoảng. | 336 Part V Optional Features int factorial int n you can t handle negative values of n better check for that condition first if n 0 throw Exception Argument for factorial negative n __FILE_ __LINE__ go ahead and calculate factorial int accum 1 while n 0 accum n n-- return accum int main int nNumberofArgs char pszArgs try this will work cout Factorial of 3 is factorial 3 endl this will generate an exception cout Factorial of -1 is factorial -1 endl control passes here catch Exception e cout Error occurred n endl wait until user is ready before terminating program to allow the user to see the program results system PAUSE return 0 This program appears much the same as the factorial program at the beginning of this chapter. The difference is the use of a user-defined Exception class that contains more information concerning the nature of the error than a simple string contains. The factorial program is able to throw the error message the illegal value and the exact location where the error occurred. FILEand__LINEare intrinsic defines that are set to the name of the source file and the current line number in that file respectively. Chapter 25 Handling Errors Exceptions 337 The catch snags the Exception object and then uses the built-in display member function to display the error message. The output from this program appears as follows Factorial of 3 is 6 Error occurred Error Argument for factorial negative - value is -1 @ cpp_programs Chap25 Press any key to continue . . . The Exception class represents a generic error-reporting class. However you can inherit from this class to provide further detail for a particular type of error. For example I can define an InvalidArgumentException class that stores the value of the invalid argument in addition to the message and location of the error class InvalidArgumentException public Exception public .