C ++ 函數後面加throw()的作用

Following declaration gives a message to the user of your class: my method 
doesn't throw any exception. Don't bother to put a try/catch block around it
when you use it.

void A::foo() throw();

It's your responsibility not to throw an exception in the definition of your
method. 
Say

void A::foo() throw() {
throw (5); // you are doomed here.
}

The compiler won't give an error on above code. But you will get a run time 
error (your program aborts) if you implemented it this way.

/////////////////////////////////

成員函數聲明後面跟上throw(),表示告訴類的使用者:我的這個方法不會拋出異常,所以,在使用該方法的時候,不必把它至於 try/catch 異常處理塊中。

聲明一個不拋出異常的函數後,你有責任保證在你的函數的實現裏面不會拋出異常。
void A::foo() throw() {
throw (5); // 程序會在這裏崩潰.(編者注:如果該異常被處理,不會崩潰)
}

編譯器不會認爲上面的代碼存在錯誤,(編者注:vc2005會給出警告:warning C4297: “foo”: 假定函數不引發異常,但確實發生了)但是,如果該異常未被上層的異常過濾器捕捉的話,會引發運行時的錯誤。

/////////////////////////////////
綜上述: 
1) 函數後面聲明 throw() 只是接口的提供者和接口的使用者間的默契或稱協議。
2) 這種協議不影響正常的異常處理流程。
3) vc2005 會在編譯器對這種協議的遵守情況進行檢查,並在爲遵守協議的情況下 給出警告。

     同理, 函數後面可以跟上 throw( int ),表示該函數可能會拋出 int型的異常。但不會拋出別的類型的異常。使用者應該注意捕獲 該函數可能拋出的int型的異常
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章