void f() throw() 表示f不允許拋出任何異常,即f是異常安全的。
void f() throw(...) 表示f可以拋出任何形式的異常。
void f() throw(exceptionType); 表示f只能拋出exceptionType類型的異常。
引別人的一個笑話:
throw() 大概會說:“噢,不管你拋什么,就是不準拋。。”
throw(...) 呵呵一笑,滿臉慈祥:“拋吧拋吧,盡情地拋吧。。。”
throw(type) 一聽急了:“那可不行,要拋也只能拋我的香煙頭,否則要是不小心把俺祖傳的金戒指拋掉就太虧了。。。”
關于C++的異常傳遞有三種方法:
1.傳值(by value)
傳值的過程中會產生臨時對象的拷貝,不能解決多態的問題,如下:myexception繼承exception,但是但確無法被正確的調用myexception的方法,造成對異常對象的切割。
1 class myexception:public exception{
2 public:
3 virtual const char* what() throw();
4 };
5 const char* myexception::what(){
6 return "myException";
7 }
8 class A{
9 public:
10 A(){}
11 void f() throw(){
12 throw myexception();
13 }
14 };
15 int main(){
16 A a;
17 try{
18 a.f();
19 }catch(exception exc){
20 cout<<exc.what();
21 }
22 }
2 public:
3 virtual const char* what() throw();
4 };
5 const char* myexception::what(){
6 return "myException";
7 }
8 class A{
9 public:
10 A(){}
11 void f() throw(){
12 throw myexception();
13 }
14 };
15 int main(){
16 A a;
17 try{
18 a.f();
19 }catch(exception exc){
20 cout<<exc.what();
21 }
22 }
運行結果:UnKnown exceptions
程序執行是會調用exception的what方法,而不是myexception的what方法。
2.傳指針(by pointer)
指針可以實現多態,但往往會將臨時對象的地址作為指針傳出去,出現懸掛指針錯誤。如果在堆上分配內存空間,又往往不知道何時刪除對象,出現to be or not to be的錯誤。
結果顯示:myException
1 class myexception:public exception{
2 public:
3 virtual const char * what() const;
4 };
5 const char* myexception::what() const{
6 return "myException";
7 }
8 class A{
9 public:
10 A(){}
11 void f() throw(){
12 throw new myexception();
13 }
14 };
15 int main(){
16 A a;
17 try{
18 a.f();
19 }catch(exception* pexc){
20 cout<<pexc->what();
21 delete pexc;
22 }
23 }
2 public:
3 virtual const char * what() const;
4 };
5 const char* myexception::what() const{
6 return "myException";
7 }
8 class A{
9 public:
10 A(){}
11 void f() throw(){
12 throw new myexception();
13 }
14 };
15 int main(){
16 A a;
17 try{
18 a.f();
19 }catch(exception* pexc){
20 cout<<pexc->what();
21 delete pexc;
22 }
23 }
3.傳引用(by reference)
傳引用是最好的方法,可以克服前面的兩個問題。
程序結果顯示:myException
1 class myexception:public exception{
2 public:
3 virtual const char * what() const;
4 };
5 const char* myexception::what() const{
6 return "myException";
7 }
8 class A{
9 public:
10 A(){}
11 void f() throw(){
12 throw myexception();
13 }
14 };
15 int main(){
16 A a;
17 try{
18 a.f();
19 }catch(exception& exc){
20 cout<<exc.what();
21 }
22 }
2 public:
3 virtual const char * what() const;
4 };
5 const char* myexception::what() const{
6 return "myException";
7 }
8 class A{
9 public:
10 A(){}
11 void f() throw(){
12 throw myexception();
13 }
14 };
15 int main(){
16 A a;
17 try{
18 a.f();
19 }catch(exception& exc){
20 cout<<exc.what();
21 }
22 }
本文轉自:http://www.cnblogs.com/CUCmehp/archive/2009/01/12/1374320.html