例外處理 (exception handling) 可以有多個 catch ,如果 catch 後的小括弧裡面放 ... ,就表示不限型態種類的任何例外 (exception) 。
舉例如下
#include <iostream>
int main(void) {
try {
if (5 < 0) {
throw 0;
}
throw 2.0;
}
catch (const int e) {
std::cout << e << std::endl;
}
catch (...) {
std::cout << "something wrong" << std::endl;
}
return 0;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:trydemo03.cpp
功能:示範 C++ 程式
作者:張凱慶
時間:西元 2013 年 1 月 */這裡拋出兩種例外,第一種為 int 型態 (type) ,第二種則是 double 型態
if (5 < 0) {
throw 0;
}
throw 2.0;catch 的部份寫了兩組,第一組為處理 int 型態的例外,第二組則是 ... ,也就是任何例外
catch (const int e) {
std::cout << e << std::endl;
}
catch (...) {
std::cout << "something wrong" << std::endl;
}這裡須注意,如果 ... 的次序放在 int 之前,發生例外就會直接執行 ... 的部份,因此 ... 放在最後有以上皆非的意義。
編譯執行結果如下

| 中英文術語對照 | |
|---|---|
| 例外處理 | exception handling |
| 例外 | exception |
| 型態 | type |
您可以繼續參考
例外處理
相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁
參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial
C++ Primer, Fourth Edition, Stanley B. Lippman...
沒有留言:
張貼留言