C++ provides us with a standard exception handling class , which is used to throw exceptions when functions in the C++ standard library are executed. The hierarchical structure of the standard exception classes provided by C++ is as follows:
It can be seen that all exception classes inherit from the exception base class. Logic_error and runtime_error under the exception class are two relatively large categories, including multiple self-classes. They are divided into tables to represent logic errors and runtime errors .
Give examples, such as:
1. When we use new to open up memory, if there is insufficient space, a bad_alloc exception will be thrown.
2. When we use dynamic_cast() to perform dynamic type conversion and fail, a bad_typeid exception will be thrown.
3. When the calculated value exceeds the maximum range represented by the type, an overflow_error exception is thrown, indicating an operation overflow. Similarly, underflow_error indicates an operation underflow.
4. When we use the string class subscript but it goes out of bounds, an out_of_range exception is thrown.
Wait...wait...please find out more on your own.
It should be noted that when using the standard exception class that comes with C++, you need to include the corresponding header file, because the exception and bad_exception classes are defined in the header file exception, the bad_alloc class is defined in the header file new, and the bad_typeid class is defined in the header file typeinfo. , the ios_base::failure class is defined in the header file ios, and other exception classes are defined in stdexcept.
Below, I will show you how to use the C++ standard exception class :
#include<iostream>#include<new>#include<stdexcept>usingnamespacestd;//Exception handling intmain(){string*s;try{s=newstring(www.dotcpp.com);cout<<s->substr( 15,5);}catch(bad_alloc&t){cout<<Exceptionoccurred:<<t.what()<<endl;}catch(out_of_range&t){cout<<Exceptionoccurred:<<t.what()<<endl;} return0;}
The running results are as follows:
Please try it out on your own and learn how to use it!