C++ Exceptions:
Exception | Description |
---|---|
std::exception | An exception and parent class of all the standard C++ exceptions. |
std::bad_alloc | This can be thrown by new. |
std::bad_cast | This can be thrown by dynamic_cast. |
std::bad_exception | This is useful device to handle unexpected exceptions in a C++ program |
std::bad_typeid | This can be thrown by typeid. |
std::logic_error | An exception that theoretically can be detected by reading the code. |
std::domain_error | This is an exception thrown when a mathematically invalid domain is used |
std::invalid_argument | This is thrown due to invalid arguments. |
std::length_error | This is thrown when a too big std::string is created |
std::out_of_range | This can be thrown by the at method from for example a std::vector and std::bitset<>::operator[](). |
std::runtime_error | An exception that theoretically can not be detected by reading the code. |
std::overflow_error | This is thrown if a mathematical overflow occurs. |
std::range_error | This is occured when you try to store a value which is out of range. |
std::underflow_error | This is thrown if a mathematical underflow occurs. |
值得注意的是一些我们经常能碰到的异常(红色):
std::bad_alloc: thrown by the standard definitions of operator new and operator new[] when they fail to allocate the requested storage space.
默认的new
是要抛出异常的,如果想不抛异常而是置指针为NULL,需要使用new(std::nothrow)。
std::bad_cast: When dynamic_cast
cannot
cast a pointer because it is not a
complete object of the required class -as in the second conversion in the
previous example- it returns a null
pointer to indicate the
failure.
If dynamic_cast
is
used to convert to a reference type
and the conversion is not possible, an exception of type bad_cast
is
thrown instead.
未捕获的异常处理方式如下:
If no handler at any level catches the exception, the special library function terminate( ) (declared in the <exception> header) is automatically called. By default, terminate( ) calls the Standard C library function abort( ) , which abruptly exits the program. On Unix systems, abort( ) also causes a core dump. When abort( ) is called, no calls to normal program termination functions occur, which means that destructors for global and static objects do not execute. The terminate( ) function also executes if a destructor for a local object throws an exception while the stack is unwinding (interrupting the exception that was in progress) or if a global or static object s constructor or destructor throws an exception. (In general, do not allow a destructor to throw an exception.)