【C++异常机制】

首先把可能会发生异常的语句放在try语句内,然后通过catch语句接异常,接异常的时候是严格按照类型匹配的(不像函数参数可以进行隐式类型转换)。而抛异常的时候,通过throw语句抛出异常,然后直接转到接收该类型的异常的catch语句处执行,throw后面的语句不再执行,抛出异常的函数后面的语句不再执行(try语句内),这是异常的跨函数特性。异常在接收后也可以不处理继续抛出,但是必须要有接异常,否则程序会挂。

下面通过一个实例分析:

#include <iostream>
using namespace std;

//可以抛出任何类型异常
void TestFunc1(const char* p)
{
	if (p == NULL)
	{
		throw 1;
	}
	else if (!strcmp(p, ""))
	{
		throw 2;
	}
	else
	{
		cout << "the string is : " << p << endl;
	}
}

//只能抛出以下类型异常 int char 
void TestFunc2(const char* p) throw(int, char)
{
	if (p == NULL)
	{
		throw '1';
	}

	cout << "the string is : " << p << endl;
}

//不抛出任何类型异常
void TestFunc3(const char* p) throw()
{
	cout << "the string is : " << p << endl;
}

int main()
{
	char buf1[] = "hello c++";
	char* buf2 = NULL;
	char buf3[] = "";

	try
	{
		//TestFunc1(buf2); //这里抛出异常,那么后面都不再执行,这是异常的跨函数特性
		//TestFunc1(buf3);
		TestFunc2(buf2);
		TestFunc3(buf1);
	}
	catch (int e) //异常严格按照类型进行匹配
	{
		switch(e)
		{
		case 1:
			cout << "the string is NULL" << endl;
			break;
		case 2:
			cout << "the string is space" << endl;
			break;
		default:
			cout << "do not know" << endl;
			break;
		}
	}
	catch (char) //可以只写类型
	{
		cout << "throw char test" << endl;
	}
	catch (...)
	{
		cout << "other err" << endl;
	}
	
	system("pause");
	return 0;
}

posted @ 2022-03-15 09:59  Mindtechnist  阅读(12)  评论(0编辑  收藏  举报  来源