1. 程式人生 > >C++異常處理(一)

C++異常處理(一)

*****************利用throw呼叫類物件******************

//exc_mean.h
#ifndef _EXC_MEAN_H_
#define _EXC_MEAN_H_
#include<iostream>
using namespace std;
class bad_hmean
{
private:
	double a;
	double b;
public:
	bad_hmean(const double x = 0, const double y = 0) :a(x), b(x){}
	void show()const;
};
class bad_gmean
{
private:
	double a;
	double b;
public:
	bad_gmean(const double x = 0, const double y = 0) :a(x), b(x){}
	void show()const;
};
void bad_gmean::show()const
{
	cout << "Sorry, the arguments of gmean() need positive number\n";
	cout << "Argument " << a << " and " << b << " are not satisfied this condition!\n";
}
void bad_hmean::show()const
{
	cout << "argument " << a << "=" << b << " is not allowed!" << endl;
}
#endif //_EXC_MEAN_H_


//main.cpp
#include<iostream>
#include<cmath>
#include"windows.h"
#include"exc_mean.h"
using namespace std;
double hmean(double x, double y) throw(bad_hmean);;
double gmean(double x, double y) throw(bad_gmean);
int main()
{
	double a, b,c,d;
	cout << "please input two double value to get\n"<<
		"its harmonic mean:(q or Q to quit!)";
	while (cin >> a >> b)
	{
		try{
			c = hmean(a, b);
			d = gmean(a, b);
		}
		catch (bad_hmean &bhm)
		{
			bhm.show();
			cout << "please input a new pair number:";
			continue;
		}
		catch (bad_gmean &bgm)
		{
			bgm.show();
			cout << "Sorry, you have no chance to try again.Good bye!\n";
			break;
		}
		cout << "The harmonic mean of " << a << " and " << b << " is:" << c << endl;
		cout << "The Geometric mean of " << a << " and " << b << " is:" << d << endl;
		cout << "please input two double value to get\n" <<
			"its harmonic mean:(q or Q to quit!)";
	}
  system("pause");
  return 0;
}

double hmean(double x, double y)
{
	if (x == -y)
	{
		throw bad_hmean(x, y);
	}
	return 2 * x*y / (x + y);
}

double gmean(double x, double y)
{
	if (x < 0 || y < 0)
		throw bad_gmean(x, y);
	return sqrt(x*y);
}

程式執行結果如下圖