星期一, 10月 26, 2009

C++課程:例外處理之修改

以下程式碼為上課提供並做修改的部分:

#include
#include
using namespace std;
class DivideByZero {
public:
DivideByZero(int n, int d) : num(n), denom(d), message("Divide by zero") {}
~DivideByZero()
{ cout << "Bye~ " << endl; }
int getNumerator() {return num;}
int getDenominator() {return denom;}
string getMessage() {return message;}
private:
int num;
int denom;
string message; };
int main()
{
int x = 5;
int y = 0;
int result;
try { if (y == 0) { throw DivideByZero(x, y); }
result = x/y; }
catch (DivideByZero e) {
cout << e.getMessage() << endl;
cout << "Numerator: " << e.getNumerator() << endl;
cout << "Denominator: " << e.getDenominator() << endl; }
cout << "Goodbye" << endl;
return 0;
}
這裡的問題是解構子會被執行兩次。
其實Throw 時及 new 出來的DivideByZero物件的建構子均有執行到的,
只是目前只有提供 DivideByZero(int n, int d)這一個建構子,
所以沒有傳參數進去就不會使用這個建構子。

改成以下語法就可以減少物件的產生:

try
{
if (y == 0)
{
throw new DivideByZero(x, y);
}
result = x/y;
}
catch (DivideByZero *e)
{
cout <<>getMessage() << endl;
cout << "Numerator: " <<>getNumerator() << endl;
cout << "Denominator: " <<>getDenominator() << endl;
delete e;
}
cout << "Goodbye" << endl;

沒有留言:

張貼留言