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;
}