如何将对象用做异常类型

         通常,引发异常的函数将传递一个对象。这样做的重要优点之一是,可以使不同的异常类型来区分不同的函数在不同情况下引发的异常。另外,对象可以携带信息,coders可以根据这些信息来确定引发异常的原因。同时,catch块可以根据这些信息来决定采取什么样的措施。

示例代码如下:

// exception_class.cpp : 定义控制台应用程序的入口点。
//using exception classses

#include "stdafx.h"
#include <iostream>
#include <cmath>     //or math.h, unix users may need
#include "exc_mean.h"

//function prototypes(函数原型)
double hmean(double a, double b);
double gmean(double a, double b);

int _tmain(int argc, _TCHAR* argv[])
{
	using std::cout;
	using std::cin;
	using std::endl;

	double x, y, z;

	cout << "Enter two numbers: ";
	while(cin >> x >> y)
	{
		try{
			z = hmean(x, y);     //可能引发bad_hmean类型的异常
			cout << "Harmonic mean of " << x << " and " << y << " is " << z << endl;
			cout << "Geometric mean of " << x << " and " << y << " is " << gmean(x, y) << endl;  
			//gmean(x, y)可能引发bad_gmean类型的异常

			cout << "Enter next set of numbers <q to quit>: ";
		}
		catch (bad_hmean &bg)
		{
			bg.mesg();
			cout << "Try again.\n";
			continue;
		}
		catch (bad_gmean &hg)
		{
			cout << hg.mesg();
			cout << "Values used: "<< hg.v1 << "," << hg.v2 << endl;
			cout << "Sorry, you don't get to play any more.\n";
			break;
		}
	}
	cout << "Bye!\n";
	cin.get();
	cin.get();

	return 0;
}

double hmean(double a, double b)
{
	if(a == -b)
		throw bad_hmean(a, b);    // 传递bad_hmean对象作为异常类型,对应由第一个catch块:catch(bad_hmean &bg)捕获

	return 2.0 * a * b / (a + b);
}
double gmean(double a, double b)
{
	if( a < 0 || b < 0)
		throw bad_gmean(a, b);   //传递bad_gmean对象作为异常类型,对应由第二个catch块:catch (bad_gmean &hg)捕获
	return std::sqrt(a * b);
}

//exc_mean.h --exception classses for hmean(), gmean()
#include <iostream>

class bad_hmean      //第一个异常返回类定义
{
private:
	double v1;
	double v2;
public:
	bad_hmean(double a = 0, double b = 0) : v1(a), v2(b) {}
	void mesg();
};

inline void bad_hmean::mesg()
{
	std::cout << "hmena(" << v1 <<"," << v2 <<"):" << "invalid arguements: a == -b\n";

}
class bad_gmean     //第二格异常返回类
{
public:
	double v1;
	double v2;
	bad_gmean(double a = 0, double b = 0) : v1(a), v2(b) {}
	const char * mesg();
};
inline const char  * bad_gmean::mesg()
{
	return "gmean() arguments should be >= 0\n";
}


运行效果如图:

如何将对象用做异常类型_第1张图片

你可能感兴趣的:(C++,对象,异常)