捕獲指定的類型
這樣的話能夠對每種異常作出不一樣的處理,例如:ios
#include <iostream> using namespace std; void A(int n){ int a = 1; float b = 0.2; double c = 0.3; if(n == 1) throw a; else if(n == 2) throw b; else if(n == 3) throw c; } int main() { int test; while(cin >> test){ try{ A(test); }catch(int i){ cout << "Catch int exception " << i << endl; }catch(float i){ cout << "Catch float exception " << i << endl; }catch(double i){ cout << "Catch double exception " << i << endl; } } return 0; }
捕獲泛型
若是想捕獲所有類型異常的話,C++ 提供了一種簡便的作法,在 catch 子句的異常聲明中使用省略號來做爲異常聲明,例如:函數
void function(){ try { /* your code */ }catch(...) { /* handler */ } }
捕獲類
例如:spa
#include <iostream> using namespace std; class Base{ public: void name(){ cout << "My name is Base" << endl; } }; void A(){ throw Base(); } int main() { try{ A(); }catch(Base &e){ e.name(); } return 0; }
也能夠捕獲 Base 的子類,而且在 Base 類的成員函數前加 virtual 實現多態,這樣的話就能夠調用子類的 name 方法,例如:code
#include <iostream> using namespace std; class Base{ public: virtual void name(){ cout << "My name is Base" << endl; } }; class Derived : public Base{ public: void name(){ cout << "My name is Derived" << endl; } }; void A(){ throw Derived(); } int main() { try{ A(); }catch(Base &e){ e.name(); } return 0; }
捕獲未指望的異常
能夠在函數名後用 throw 來聲明該函數可能拋出的異常,例如:ci
#include <iostream> using namespace std; void A() throw (int, float) { int a = 1; float b = 0.2; double c = 0.3; throw c; } int main() { try{ A(); }catch(...){ cout << "Catch exception" << endl; } return 0; }
可是,若是函數拋出的異常類型未在聲明範圍內的話,程序就會發生崩潰:io
運行結果:function
terminate called after throwing an instance of 'double' Aborted (core dumped)
即便你使用了 catch(...) ,但它也捕獲不到,異常會繼續向上彙報,最終被系統默認的函數進行處理。class
但咱們可使用 set_unexpected (unexpected_handler func) 這個函數來修改默認的處理方法,來實現本身的處理方式。test
未實現捕獲的異常
假如函數拋出一個 double 的異常,但在咱們捕獲的函數中沒有實現 double 類型的捕獲,固然也沒有使用 catch(...),這種狀況和未指望的異常差很少,它也會上報系統,調用系統默認的處理函數。一樣咱們也能夠更改這個默認函數,使用以下方法:stream
terminate_handler set_terminate (terminate_handler func)
示例程序:
#include <iostream> void exception(){ std::cout << "my_terminate" << std::endl; } int main() { std::set_terminate(exception); throw 0; return 0; }
運行結果:
my_terminate Aborted (core dumped)