C ++ Exception Handling
C ++ Exception Handling
Translated from c ++ complete refrence 3rd Chapter 38
The standard c ++ library defines two exception-related libraries, <exception> and <stdexcept>. Exceptions are usually used to report errors.
<Exception>
<Exception> defines classes, declarations, and functions related to exception handling.
Class exception {
Public:
Exception () throw ();
Exception (const char * const &);
Exception (const char * const &, int );
Exception (const bad_exception & ob) throw ();
Virtual ~ Exception () throw ();
Exception & operator = (const exception & ob) throw ();
Virtual const char * what () const throw ();
};
Class bad_exception: public exception {
Public:
Bad_exception () throw ();
Bad_exception (const bad_exception & ob) throw ();
Virtual ~ Bad_exception () throw ();
Bad_exception & operator = (const bad_exception & ob) throw ();
Virtual const char * what () const throw ();
};
The exception class is the parent class of all exceptions in the c ++ library. The unexpected () function throws the bad_exception type. Each exception class overwrites what () to return a string that describes the exception.
Some important classes are inherited from the exception class. The first one is bad_alloc, Which is thrown when the new operation fails. The other is bad_typeid, Which is thrown when the typeid operation is used incorrectly.
<Exception> define the following declaration
Type |
Definition |
Terminate_handler |
Typedef void (* terminate_handler )(); |
Unexpected_handler |
Typedef void (* unexpected_handler )(); |
<Exception> define the following functions
Function |
Description |
Terminater_handler set_terminate (terminate_handler fn) throw (); |
Specify the function called when the program ends. The old function pointer is returned. |
Unexpected_handler set_unexpected (unexpected_handler fn) throw (); |
Same as above. |
Void terminate (); |
This function is called when an exception is processed at the end. The default value is abort. |
Void unexpected (); |
Same as above |
<Stdexcept>
<Stdexcept> defines some standard exception classes. There are two categories: logical errors and runtime errors. The running error is beyond the control of the programmer.
All logical errors are inherited from logic_error.
Exception |
Description |
Domain_error |
Domain Error |
Invalid_argument |
Invalid Parameter |
Length_error |
Generally, the size of the created object is too large. |
Out_of_range |
Access to the outside world |
Runtime errors are inherited from runtime_error
Exception |
Description |
Overflow_error |
Overflow |
Range_error |
Beyond the indicated range |
Underflow_error |
Underflow |