2010-04-25 208 views
22

此代碼有效;在C++中拋出異常異常

int at(int index) { 
    if(index < 1 || index >= size) 
    throw 0; 

    return x[index]; 
} 

但這並不

int at(int index) { 
    if(index < 1 || index >= size) 
    throw std::out_of_range; 

    return x[index]; 
} 

我得到的錯誤 「之前預計主要表達 ';'」。現在...我很驚訝,因爲我知道的std :: out_of_range存在,我有

#include <stdexcept> 
+2

這兩個函數有什麼區別? – kennytm 2010-04-25 19:58:51

+0

oops,複製粘貼錯誤,現在沒關係。 – Suugaku 2010-04-25 20:00:22

+6

爲什麼是0越界? – 2010-04-25 22:23:28

回答

62

更換throw std::out_of_range;throw std::out_of_range ("blah");。即你需要創建一個對象,你不能拋出一個類型。