C + + exception handling
Translated from C + + complete refrence 3rd Chapter
The standard C + + library defines two exceptions-related libraries,<exception> and <stdexcept>. Exceptions are commonly used to report errors.
<exception>
<exception> defines classes, declarations, and functions that are 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 for all exceptions in the C + + library. the Unexpected () function throws the bad_exception type. Each exception class overrides what () to return a string that describes the exception.
Some of the 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 |
Defined |
Terminate_handler |
typedef void (*terminate_handler) (); |
Unexpected_handler |
typedef void (*unexpected_handler) (); |
<exception> define the following function
Function |
Describe |
Terminater_handler set_terminate (terminate_handler fn) throw (); |
Specifies the function that is called at the end of the program, and returns an old function pointer. |
Unexpected_handler set_unexpected (unexpected_handler fn) throw (); |
Ditto. |
void terminate (); |
This function is called by default abort () when there is an exception at the end of processing. |
void Unexpected (); |
Ditto |
<stdexcept>
<stdexcept> defines a number of standard exception classes. There are two main categories: logic errors and run-time errors. Where run-time errors are not controlled by the programmer.
Logical errors are inherited from logic_error
| exception |
description |
| |
domain error |
| invalid_argument |
illegal parameters |
| length_error |
Usually the object being created is too large for the given size |
| out_of_range< /span> |
access hyper-bounds |
Run-time errors are inherited from runtime_error
Abnormal |
Describe |
Overflow_error |
Overflow |
Range_error |
Beyond the Presentation range |
Underflow_error |
Underflow |
C + + exception handling