1. 程式人生 > >C++中用try - catch處理異常的情況

C++中用try - catch處理異常的情況

正常程式碼放在try塊,catch中捕獲try塊用throw關鍵字丟擲的異常。

例如:

try { //將可能出現異常的情況放到try塊
if ( a >12 ) throw 12; // a >12時丟擲,若成立下面程式碼就不會再執行了
if ( a < 10 ) throw error;

throw xxx ; //其他異常情況丟擲
}

catch ( int result ) { //由於上面丟擲的是整數,所以用int
cout << “result is:” << result << endl;
b = result + 1;
}

catch (char * result ) { //若上面丟擲的是字元,所以用char
cout << “result is:” << result << endl;
b = result + 1;
}