C++/stdexcept

本頁使用了標題或全文手工轉換
維基教科書,自由的教學讀本
< C++

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