异常的概念

异常的处理机制允许程序在运行时就出现的问题进行相应的处理。异常可以使得我们将问题的发现和问题的解决分开,程序的一部分负责检测,而另一部分负责处理,检测环节无需过多的细节。

当发生错误时,C语言主要通过错误码的形式处理错误,错误码本质是将不同的错误信息进行编号,拿到错误码我们还需要进行查询才能得知具体是什么错误,比较麻烦。而异常则是抛出一个对象,这个对象可以涵盖对于这个错误的各种信息。

2.异常的抛出和捕获

当程序出现问题时,我们将会通过【throw】抛出一个对象来引发一个异常,该对象的类型以及当前的位置决定了由哪个catch来处理。

被选中的catch是调用链中与给对象类型匹配且离抛出位置最近的那一个。根据抛出异常对象的类型和内容,程序的抛出异常部分会告知到底发生了什么错误。

当throw执行时,thorw后面的代码将不再执行,就像break一样直接跳出。程序的执行从throw的位置直接跳到匹配的catch位置,catch可能在同一个函数中,有可能在调用链的其他函数中。这里有两个注意点:1.沿着调用链的函数可能会提前退出 ,2.一旦程序开始执行抛异常,沿着调用链创建的对象都将销毁

抛出异常对象后,会产生一个异常对象的临时对象,因为抛出的异常可能的局部对象。这个临时对象会在catch语句后销毁。

3.栈展开

抛异常后,程序会暂停当前的执行,开始寻找与之匹配的catch子句。首先检查throw本身是否在try内部,如果在则查找有没有匹配的catch语句,如果匹配就跳到catch是位置进行处理。

如果不匹配或者没有try内部,则退出当前函数,继续在外层调用函数链中查找,上述过程被称为栈展开。

如果一直查找到main函数,依然没有匹配的catch语句,那么程序就会调用标准库的terminate函数终止程序。

如果在后续的查找过程中匹配到了相应的catch语句,那么就执行catch语句以及下面的代码。

代码语言:javascript

AI代码解释

#include<iostream>
#include<string>
using namespace std;

double Divide(int a, int b)
{
	try
	{
		//当b为0时抛出异常
		if (b == 0)
		{
			string s("除数为0!");
			throw s;
		}
		else
		{
			return (double)a / b;
		}
	}
	catch(int errid) //抛异常时,类型不匹配。结束当前函数
	{
		cout << errid << endl;
	}
}

void Func()
{
	int len, time;
	cin >> len >> time;

	try
	{
		cout << Divide(len, time) << endl;
	}
	catch (string errid)//类型匹配,直接跳到这里执行代码
	{
		cout << errid << endl;
		cout << __FUNCTION__ << ":" << __LINE__ << endl;
	}

}



int main()
{
	while(1)
	{
		try
		{
			Func();
		}
		catch (string errid)//类型匹配,但只会跳到最近的catch进行匹配
		{
			cout << errid << endl;
			cout << __FUNCTION__ << ":" << __LINE__ << endl;
		}
	}
}
//如果抛异常时,所有catch都不匹配就会报错,程序停止。

4.查找匹配的处理代码

一般情况下抛出的对象类型要和catch的接收类型完全一样,如果有多个catch与之匹配,会匹配其最近的catch。

但是也又特殊情况,允许从非常量向常量的类型转化,也是就权限缩小。允许数组转换成指向数组的指针,允许函数转换成函数指针;允许派生类转换为基类,这个在实践中非常常用,一般抛异常都是用这个设计的。

抛异常的匹配如果到了main函数仍然匹配不上,就会报错,程序停止。但是一般来说不是发生严重的错误,我们是不期望程序停止的,所以在main函数的最后我们一般会使用 catch(...),它可以捕捉任意类型的异常,但是并不能知道具体的异常是什么。

通过继承基类实现不同类型是异常,为了统一捕捉在实践中我们一般都是在main函数中使用catch,try一定要和从catch一起使用。

代码语言:javascript

AI代码解释

#include<iostream>
#include<thread>
using namespace std;
//每个异常模块都是继承Exception的派生类,每个异常模块都可以添加自己的数据
//最后捕获的时候,我们捕获基类就可以了


//不同的异常类型都通过继承基类来实现
class Exception
{
public:
	Exception(const string& errmsg,int id)
		:_errmsg(errmsg)
		,_id(id)
	{ }

	virtual string what() const
	{
		return _errmsg;
	}

	int getid() const
	{
		return _id;
	}

protected:
	string _errmsg;
	int _id;
};

class SqlException : public Exception
{
public:
	SqlException(const string& errmsg,int id,const string& sql)
		:Exception(errmsg,id)
		,_sql(sql)
	{ }

	virtual string what() const
	{
		string str = "SqlException:";
		str += _errmsg;
		str += "->";
		str += _sql;
		return str;
	}

private:
	const string _sql;
};

class CacheException : public Exception
{
public:
	CacheException(const string& errmsg, int id)
		:Exception(errmsg, id)
	{ }

	virtual string what() const
	{
		string str = "CacheException:";
		str += _errmsg;
		return str;
	}
};

class HttpException : public Exception
{
public:
	HttpException(const string& errmsg, int id, const string& type)
		:Exception(errmsg, id)
		, _type(type)
	{
	}
	virtual string what() const
	{
		string str = "HttpException:";
		str += _type;
		str += ":";
		str += _errmsg;
		return str;
	}
private:
	const string _type;
};

void SQLMgr()
{
	if (rand() % 7 == 0)
	{
		throw SqlException("权限不足", 100, "select * from name = '张三'");
	}
	else
	{
		cout << "SQLMgr调用成功" << endl;
	}
}

void CacheMgr()
{
	if (rand() % 5 == 0)
	{
		throw CacheException("权限不足", 100);
	}
	else if (rand() % 6 == 0)
	{
		throw CacheException("数据不存在", 101);
	}
	else
	{
		cout << "CacheMgr 调用成功" << endl;
	}

	SQLMgr();
}

void HttpServer()
{
	if (rand() % 3 == 0)
	{
		throw HttpException("请求资源不存在", 100, "get");
	}
	else if (rand() % 4 == 0)
	{
		throw HttpException("权限不足", 101, "post");
	}
	else
	{
		cout << "HttpServer调用成功" << endl;
	}

	CacheMgr();
}


int main()
{
	srand(time(0));

	while(1)
	{
		this_thread::sleep_for(chrono::seconds(1));

		try
		{
			HttpServer();
		}
		catch (const Exception& e) //派生类可以向基类进行转换,这里用基类进行捕获即可
		{
			cout << e.what() << endl;
		}
		catch (...)//为防止出现异常不匹配导致程序终止,使用 【...】 进行匹配
		{
			cout << "未知异常" << endl;
		}
	}
}

5.异常重新抛出

有时catch捕捉到一个异常后,需要对错误进行分类,对其中某一个错误进行特殊处理,而其他的异常要重新抛出给外层调用链处理。异常捕获后,直接使用throw,就可以重新抛出。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐