Defining an Exception Class to Represent the Type of Problem That Might Occur

Figure 17.1 defines class DivideByZeroException as a derived class of Standard Library class runtime_error (from header <stdexcept>). Class runtime_error—a derived class of exception (from header <exception>)—is the C++ standard base class for representing runtime errors. Class exception is the standard C++ base class for exception in the C++ Standard Library. (Section 17.10 discusses class exception and its derived classes in detail.) A typical exception class that derives from the runtime_error class defines only a constructor (e.g., lines 11–12) that passes an error-message string to the base-class runtime_error constructor. Every exception class that derives directly or indirectly from exception contains the virtual function what, which returns an exception object’s error message. You’re not required to derive a custom exception class, such as DivideByZeroException, from the standard exception classes provided by C++. However, doing so allows you to use the virtual function what to obtain an appropriate error message. We use an object of this DivideByZeroException class in Fig. 17.2 to indicate when an attempt is made to divide by zero.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.37.129