Exceptions thrown by the C + + language itself or the standard library are exception subclasses, known as standard exception. You can use the following statement to match all standard exceptions:
Try { // The statement that could throw an exception }catch(Exception &e ) {// The statement that handles the exception }
References are used to improve efficiency. If you do not use a reference, you will go through the process of copying the object once (copying the object to invoke the copy constructor).
The exception class is located in the <exception> header file, which is declared as:
classException { Public: Exception ()Throw();//constructor FunctionException (Constexception&)Throw();//copy Constructorexception&operator= (Constexception&)Throw();//operator Overloading Virtual~exception ()Throw();//Virtual destructor Virtual Const Char* What ()Const Throw();//Virtual Functions}
What needs to be explained here is the What () function. The What () function returns a string that recognizes the exception, just as its name "What" can tell you roughly what the exception is. However, the C + + standard does not specify the format of the string, the implementation of each compiler is different, so the return value of what () is for reference only.
Shows the inheritance hierarchy of the exception class:
Figure: The inheritance hierarchy of the exception classes and their corresponding header files
Let's take a look at the direct derived classes of the exception class:
Exception name |
Description |
Logic_error |
Logic error. |
Runtime_error |
Run-time error. |
Bad_alloc |
The exception that is thrown when memory failure is allocated using new or new[]. |
Bad_typeid |
A NULL pointer is manipulated using typeid, and the pointer is a class with a virtual function, and the Bad_typeid exception is thrown. |
Bad_cast |
The exception that is thrown when using the dynamic_cast conversion fails. |
Ios_base::failure |
The exception that occurred during the IO process. |
Bad_exception |
This is a special exception, if the bad_exception exception is declared in the exception list of the function, and if an exception is thrown inside the function that does not have an exception, if an exception is thrown in the called Unexpected () function, any type will be replaced with bad_exception Type. |
C + + Learning Exception class