一次C++作业 try-throw-catch

1、设计一个异常RangeError类响应输入的数不在指定范围内,实现并测试这个类。

/*设计一个异常RangeError类响应输入的数不在指定范围内,实现并测试这个类。*/
#include<iostream>
#include<exception>
using namespace std;

class RangeError
{
public:
	RangeError()
	{
		cout << "Please input a Integer Number(0~10000):";
		int abc;
		cin >> abc;
		try
		{
			if (abc <= 10000 && abc >= 0)
			{

				cout << "Your Integer Number is:" << abc;
			}
			else
			{
				throw 1;
			}
		}
		catch (int)
		{
			cout << "Your Integer Number is out";
		}
	}
};
int main()
{
	RangeError();
}

2、定义一个异常类CException,有成员函数Reason(),用来显示异常的类型,定义函数fn1()触发异常,在主函数的try模块中调用fn1(),在catch模块中捕获异常,观察程序的执行流程。

#include<iostream>
using namespace std;
class CException
{
public:
	CException() {}
	~CException() {}
	const char* Reason() const
	{
		return "CException类中异常";
		throw Reason();
	}
};
void fn1()
{
	cout << "在子函数fn1()中触发CException类异常" << endl;
	throw CException();
}

int main()
{
	cout << "进入主函数" << endl;
	try
	{
		cout << "到达try模块中,即将调用子函数" << endl;
		fn1();
	}
	catch (CException C)
	{
		cout << "在catch模块中,通过函数fn1(),捕获到CException类型异常,即将调用成员函数Reason()" << endl;
		cout << C.Reason() << endl;
	}
	catch (char* str)
	{
		cout << "捕获到其他异常类型:" << str << endl;
	}
	cout << "回到主函数,异常已被处理。" << endl;
}
原文地址:https://www.cnblogs.com/xiaotian66/p/13257202.html