tailieunhanh - A Complete Guide to Programming in C++ part 65

A Complete Guide to Programming in C++ part 65. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | DEFINING YOUR OWN ERROR CLASSES 619 Exception Class Members When an exception is thrown the exception object type determines which exception handler will be executed. For this reason an exception class does not need to have any members. However an exception class can contain data members and methods just like any other class. This makes sense as locally defined non-static objects are destroyed when an exception has been thrown and the stack is unwound. Thus the exception handler can no longer access the previously existing objects. You can use the data members of error classes to rescue data threatened by an error condition. For example you can store data important for exception handling in an exception object. The Exception Class MathError The exception class MathError is defined opposite. The calc function throws an exception when a number input by a user is negative or 0. When an exception is thrown Example throw MathError Division by 0 the error message is stored in the exception object. The exception handler can then use the getMessage method to evaluate the message. Exception Hierarchies New exception classes can be derived from existing exception classes. A base class will normally represent a general error type and specific errors will be represented by derived classes. Thus the exception class MathError could be defined to represent general errors in mathematical computations but it would make sense to define derived exception classes for special cases such as Division by 0 or Arithmetic overflow. You could call these classes DivisionByZero and OverflowError for example. Be aware of the following rules for exception handlers in this context given that T is a derived exception class special errors of this type are handled by the exception handler if T is a base class the handler will also catch the exception objects thrown by derived classes thus providing similar handling for generic and specific errors. 620 CHAPTER 28 EXCEPTION HANDLING STANDARD EXCEPTION

TỪ KHÓA LIÊN QUAN