小猿日記(5)- 520特別篇
1217
2025-04-02
throw 是C++中的關鍵字,用來拋出異常。如果不使用 throw 關鍵字,try 就什么也捕獲不到;上節提到的 at() 函數在內部也使用了 throw 關鍵字來拋出異常。
throw 既可以用在標準庫中,也可以用在自定義的函數中,拋出我們期望的異常。throw 關鍵字語法為:
throw exceptionData;
#include
#include
using namespace std;
char get_char(const string &, int);
int main(){
string str = "c plus plus";
try{
cout< cout< }catch(int e){ if(e==1){ cout<<"Index underflow!"< }else if(e==2){ cout<<"Index overflow!"< } } return 0; } char get_char(const string &str, int index){ int len = str.length(); if(index < 0) throw 1; if(index >= len) throw 2; return str[index]; } 不被建議的用法 double func (char param) throw (int); double func (char param) throw (int, char, exception); double func (char param) throw (); #include #include using namespace std; char get_char(const string &, int) throw(char, exception); int main(){ string str = "c plus plus"; try{ cout< cout< }catch(int e){ if(e==1){ cout<<"Index underflow!"< }else if(e==2){ cout<<"Index overflow!"< } } return 0; } char get_char(const string &str, int index) throw(char, exception){ int len = str.length(); if(index < 0) throw 1; if(index >= len) throw 2; return str[index]; } C++
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。