
例外處理可以有多個 catch ,如果 catch 後的小括弧裡面放 ... ,就表示不限型態種類的任何例外。
舉例如下
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | int i = -1; |
| 005 | |
| 006 | try { |
| 007 | if (i > 0) { |
| 008 | throw 0; |
| 009 | } |
| 010 | throw 2.0; |
| 011 | } |
| 012 | catch (const int e) { |
| 013 | std::cout << e |
| 014 | << std::endl; |
| 015 | } |
| 016 | catch (...) { |
| 017 | std::cout << "something wrong" |
| 018 | << std::endl; |
| 019 | } |
| 020 | |
| 021 | return 0; |
| 022 | } |
| 023 | |
| 024 | /* Kaiching Chang |
| 025 | u0602.cpp |
| 026 | 2014-02 */ |
這裡拋出兩種例外,第一種為 int 型態 (type) ,第二種則是 double 型態
| 007 | if (i > 0) { |
| 008 | throw 0; |
| 009 | } |
| 010 | throw 2.0; |
catch 的部份寫了兩組,第一組為處理 int 型態的例外,第二組則是 ... ,也就是任何例外
| 012 | catch (const int e) { |
| 013 | std::cout << e |
| 014 | << std::endl; |
| 015 | } |
| 016 | catch (...) { |
| 017 | std::cout << "something wrong" |
| 018 | << std::endl; |
| 019 | } |
這裡須注意,如果 ... 的次序放在 int 之前,發生例外就會直接執行 ... 的部份,因此 ... 放在最後有以上皆非的意義。
編譯執行結果如下
| $ g++ u0602.cpp |
| $ ./a.out |
| something wrong |
| $ |
continue ...
沒有留言:
張貼留言