Thursday, November 08, 2012

C++ 範例程式 : try-catch

程式隨機產生整數, 並判斷是奇數或偶數.
程式碼 include iostream cstdlib ctime

using namespace std;

void func(int);
void errHandle(int);

int main()
{
	char choice;
	int num;

	srand(time(0));

	while(choice != 'N' && choice != 'n')
	{
		try{
			num = rand()%100+1;
			cout << "###  " << num << "  ";
			func(num);
		}
		catch(int errValue){
			errHandle(errValue);
		}

		cout << endl << "想要繼續玩嗎? ( Y / N ) ";
		cin >> choice;
		cout << endl;
	}

	return 0;
}

void func(int a)
{
	if(a%2)
		throw 7777777;
	else
		throw 5168888;
}

void errHandle(int e)
{
	switch(e)
	{
		case 7777777:	cout << "發現奇數" << endl;	break;
		case 5168888:	cout << "發現偶數" << endl;	break;
		default:	cout << "不明狀態碼" << endl;	break;
	}
}

No comments: