C++语言本身或者标准库抛出的异常都是exception的子类,称为标准异常,在exception头文件中被定义。
exception类中有一个名为what()的虚函数,它返回一个字符串,该字符串的特征随实现而异。
#include<exception>
class bad_hmean : public exception
{
public:
const char * what()
{
return "bad arguments to hmean()";
}
...
};
class bad_gmean : public exception
{
public:
const char * what()
{
return "bad arguments to gmean()";
}
...
};
从exception中派生而来的异常有:
- logic_error描述了典型的逻辑错误:
- 异常length_error用于指出没有足够的空间来执行所需的操作;
- 异常domain_error指出参数不在定义域区间内;
- 异常out_of_range用常用于指示所以错误;
- 异常invalid_argument指出给函数传递了一个意料外的值。
-
runtime_error异常系列描述了可能在运行期间发生但难以预计和防范的错误:
range_error异常指出计算结果可能不在函数允许的范围之内,但没有发生上溢或下溢错误的情况。 -
logic_error系列异常表明存在可以通过编程修复的问题,而runtime_error系列异常表明存在无法避免的问题。
bad_alloc异常和new
头文件new包含bad_alloc类的声明,对于使用new导致的内存分配问题,会引发bad_alloc异常。
- 空指针和new:
很多代码是在new失败时返回空指针时编写的,C++标准提供了一种在失败时返回空指针的new的开关,名为nothrow:
int * pi = new (std::nothrow) int;
int * pa = new (std::nothrow) int[500];