Template:C++ Standard library

stdexceptC++标准程式库中的一个头文件,定义了C++标准中的一些表示异常的类 ,这些类都是从std::exception为基类派生出来的。可分作逻辑错误(logic error)与运行时刻错误(run-time error)两个类别。

逻辑错误 编辑

由程序的错误引发。这些表示异常的类都是从logic_error基类派生。包括:

  • domain_error:函数的定义域错误。这里是指数学意义上的定义域(domain)[1]。例如,出生月份的值应该是1至12(计算机内部也可能表示为0-11),如果值为13,则就是domain error。
  • invalid_argument:函数的参数的格式错误。
  • length_error:产生一个包含太长的内容对象。例如,设定一个vector最大长度为10,然后给它添加11个元素。
  • out_of_range:常用于C++的数组、字符串、array、vector是否越界访问。

运行时刻错误 编辑

由库函数或者运行时刻系统(一般指由C++编译器提供的代码)。这些表示异常的类都是从runtime_error 基类派生。包括:

  • overflow_error:算术溢出错误。
  • range_error:用于值域错误的错误。
  • underflow_error:算术下溢出错误

例子程序 编辑

#include <stdexcept>
#include <math.h>
#include <stdio.h>
using namespace std;

float MySqrRoot(float x)
{
	// sqrt is not valid for negative numbers.
	if (x < 0) throw domain_error("input argument must not be negative.");

	return sqrt(x);
}

int main()
{
	printf("%f\n",MySqrRoot(4.0));
	try{
		MySqrRoot(-1.0);
	}
	catch(domain_error& s){
		printf("catch a domain_error---%s\n",s.what());
	}
	return 0;
}

运行后,输出结果:

2.000000
catch a domain_error---input argument must not be negative.

参考文献 编辑

  1. std::domain_error Class Reference