首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【C++11】异常

【C++11】异常

作者头像
Yuzuriha
发布2026-01-14 19:09:57
发布2026-01-14 19:09:57
680
举报
文章被收录于专栏:Linux网络Linux网络

前言 上文我们学习到了C++11中类的新功能【C++11】类的新功能-CSDN博客 本文我们来学习C++下一个新语法:异常

1.异常的概念

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

当发生错误时,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
复制
#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
复制
#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,就可以重新抛出。

代码语言:javascript
复制
#include<iostream>
#include<string>
#include<thread>
using namespace std;

//以下程序模拟展示聊天时发送消息的情况
//若不是网络信号导致无法发送,则抛出异常
//若是网络信号不好时抛出异常,尝试多次发送

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 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 _SeedMsg(const string& s)
{
	if (rand() % 2 == 0)
	{
		throw HttpException("网络不稳定,发送失败", 102, "put");
	}
	else if (rand() % 7 == 0)
	{
		throw HttpException("对方不是你好友", 103, "put");
	}
	else
	{
		cout << "发送成功" << endl;
	}
}

void SeedMsg(const string& s)
{
	for (int i = 0; i < 4; i++)
	{
		try
		{
			_SeedMsg(s);
		}
		catch (Exception& e)
		{
			if (e.getid() == 102)
			{
				//重新尝试
				if (i == 3)
				{
					//网络信号太差,不再过多尝试,重新抛出
					throw;
				}

				cout << "开始第" << i + 1 << "次尝试" << endl;
			}
			else
			{
				//异常重新抛出
				throw;
			}
		}
	}
}


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

	while(1)
	{
		this_thread::sleep_for(chrono::seconds(1));
		try
		{
			SeedMsg("hello");
		}
		catch (Exception& e)
		{
			cout << e.what() << endl;
		}
	}
}

6.异常安全问题

当执行throw语句时,throw后面的语句将不再执行。当执行throw这个语句要跳出这个函数去匹配catch,但是这个函数之前申请了空间。这就会造成内存泄漏。

出现这种情况就需要我们重新捕获异常,释放资源后再重新抛出。这种处理方式是不好的,下篇文章我会讲到智能指针,使用智能指针来解决这个问题是更好的方法。

7.异常规范

对于用户和编译器而言,预先知道函数会不会抛异常是很有意义的,这有助于简化调用函数的代码。

C++98中函数后面加 throw( ),表示不会抛异常。函数后面加 throw(类型1,类型2,....),表示可能会抛出异常,如果会抛出多个类型的异常,使用逗号隔开。

C++11中表示方式会更简便一些,函数后面加noexcept表示不会抛出异常。而函数后面什么都不加则表示可能会抛出异常。

不过很搞笑的是,如果一个函数后面加了noexcept,但是函数包含throw语句或者包含可能会抛异常的函数,编译器会顺利的编译通过。但是当这个函数真正抛出异常时,程序会报错停止。

noexcept(函数调用表达式) 还可以作为一个运算符,去检查函数是否可能会抛异常。如果不会抛异常返回true,如果可能会抛异常返回fasle

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2026-01-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.异常的概念
  • 2.异常的抛出和捕获
  • 3.栈展开
  • 4.查找匹配的处理代码
  • 5.异常重新抛出
  • 6.异常安全问题
  • 7.异常规范
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档