搜尋此網誌

2011年7月15日 星期五

C++ 例外處理(Exception Handler)

當函式(Function),throw(丟)出例外的時候,要用一個try..catch的block把這個問題處理掉或顯示出來給使用者知道.範例程式如下:紅色字的部分是exception的運用,
#include <iostream>
using namespace std;
void sum(int, int);

int main() {
int a=1;
int b=1;

try {
sum(a, b);
} catch (const char * s) {// start of exception handler
cout << s <<endl;
}

return 0;
}
void sum(int a, int b) {
if (a==b) {

throw "This Combination is unacceptable!!";

}
cout << a+b<<"\n";
}






紅色字的部分是表示當function sum(int,int)在try block拋出string的錯誤訊息時,catch block(區塊)要把此錯誤訊息印出來.


Exception class(例外類別)



前一個範例是拋出字串,這一個範例是拋出例外類別.使用這一個方法的好處是我們可以為exception分類出不同類別,以方便辨識.另外一方面,也提升了重用性(re-usability).


#include <iostream>
using namespace std;

class Exception {
public:
void mesg() {
cout << "Exception Occurred !!"<<endl;
}
};
void sum1(int, int) throw (Exception);

int main() {
int a=1;
int b=1;
try {
sum1(a, b);
} catch (Exception & ex) {// start of exception handler
ex.mesg();
}

return 0;
}

void sum1(int a, int b) throw (Exception) {
if (a==b) {
throw Exception();
}
cout << a+b<<"\n";
}



解說:
第一部分是宣告一個Exception class(例外類別)
第二部分部分只是把拋出字串,改為拋出此例外類別.
第三部分部分是函式的實做.要記得在定義define(定義)以及declaration(宣告)的時候加上throw關鍵字指定要丟出何種類外類別.

宏達電也不適合買進

宏達電從高點跌下來後,融資餘額屢創新高,這不是好現象
況且電子產品的價格,以及利潤會隨著競爭者的加入
和產品的普及化而降低,所以最賺錢的時候已漸漸遠離
用這麼高的價錢來看待這檔股票,似乎要審慎考慮一番.

C++ Function Templates (函式模板)

如果寫了一個function ,ex:兩個整數相加


void sum(int , int);


這樣寫的話可以將整數相加,若是同樣的用法要將兩個double(也就是浮點數)相加的時候,還要再寫一個版本給浮點數使用,這種情況可以運用function template來解決


先宣告function template: 大寫 T可代表任意型態的變數


template <class T> void sum(T , T);


在程式碼實作的部分


void sum(T a, T b) {
cout << a+b;
}


下列是完整的程式:


#include <iostream>
using namespace std;
template <class T> void sum(T, T);

int main() {
int a=1, b=2;
double c=1.1, d=2.2;
sum(a, b) ;
sum(c, d) ;
return 0;
}
template <class T> void sum(T a, T b) {
cout << a+b<<"\n";
}


接下來要介紹(Overloaded Templates)多載化的模板


如果sum()這個函式的名字不變,但傳入的參數改為三個,
那麼這種情形便稱作多載,多載化的版本也是要先宣告template,然後在實做出來.
請注意紅色字的部分是新增出來的多載化的程式碼.





#include <iostream>
using namespace std;
template <class T> void sum(T, T);
template <class T> void sum(T, T, T);

int main() {
int a=1, b=2;
double c=1.1, d=2.2 ,e=3.3;
sum(a, b) ;//3
sum(c, d) ;//3.3
sum(c, d, e)//6.6 ;
return 0;
}
template <class T> void sum(T a, T b) {
cout << a+b<<"\n";
}

template <class T> void sum(T a, T b, T c){
cout << a+b+c<<"\n";
}