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