当前位置: 首页 > news >正文

c++进阶之----异常

1. 异常处理的基本概念

异常处理是 C++ 中一种用于处理运行时错误的机制,允许程序在遇到错误时优雅地处理问题,而不是直接崩溃。异常处理的核心是通过 trycatchthrow 关键字来实现,它允许程序在遇到错误时优雅地处理问题,而不是直接崩溃。C++11 对异常处理机制进行了改进和扩展,使得异常的使用更加灵活和安全

异常处理的核心是通过 trycatchthrow 关键字来实现:

  • try:包含可能引发异常的代码。

  • catch:捕获并处理异常。

  • throw 表达式:抛出一个异常。

 2. 代码示例

我们写下如下代码,来一起深入研究一下throw catch的特性

#include<iostream>
#include<string>
using namespace std;
double Divide(int a, int b)
{
	try
	{
		// 当b == 0时抛出异常
		if (b == 0)
		{
			string s("Divide by zero condition!");
			//int a = 0;
			//double d=0;
			throw s;
			//throw a;
			//throw d;
		}
		else
		{
			return ((double)a / (double)b);
		}
	}
	catch (int errid)
	{
		cout <<"devide" << errid << endl;
	}
}

void Func()
{
	int len, time;
	cin >> len >> time;
	try
	{
		cout << Divide(len, time) << endl;
	}
	catch (const char* errmsg)
	{
		cout << errmsg << endl;
	}
	cout << __FUNCTION__ << ":" << __LINE__ << "行执行" << endl;
}

int main()
{
	while (1)
	{
		try
		{
		/*	int x = 0;
			cout << x << endl;*/
			Func();
		}
		catch (const string& errmsg)
		{
			cout << errmsg << endl;
			// 记录项目
		}
	}

	return 0;

首先我们让代码先这样运行一下,1)先输入0 5 正常,在输入5 0,抛异常 此时我们的异常信息是string,那么catch也要找与之匹配相同的才能捕捉到,2)同理屏蔽s的部分,打开a,观察现象,看异常是在哪里捕捉的,3)之后在同时打开s和a,在观察现象,不难发现异常只要抛出去程序就会停在那里,4)最后屏蔽s,a,打开d,输入5 0,观察现象

1)部分

2)部分

3)部分

 

4)部分

 

3. 查找匹配的处理代码

1) 一般情况下 抛出对象和catch是类型完全匹配 的,如果有 多个类型匹配的,就选择离他位置更近的那个 。 但是也有一些例外,允许从非常量向常量的类型转换,也就是权限缩小;允许数组转换成指向数组元素类型的指针,函数被转换成指向函数的指针;允许从派生类向基类类型的转换,这个点非常实用,实际中继承体系基本都是用这个方式设计的。
2) 如果到main函数,异常仍旧没有被匹配就会终止程序,不是发生严重错误的情况下,我们是不期望程序终止的,所以一 般main函数中最后都会使用catch(...),它可以捕获任意类型的异常 ,但是是不知道异常错误是什么。
#include<thread>
// 一般大型项目程序才会使用异常,下面我们模拟设计一个服务的几个模块
// 每个模块的继承都是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;
		}
	}
	return 0;
}

4 异常重新抛出

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

 可以类比为“传球”

#include<thread>
 //一般大型项目程序才会使用异常,下面我们模拟设计一个服务的几个模块
 //每个模块的继承都是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();
}

// 下面程序模拟展示了聊天时发送消息,发送失败补货异常,但是可能在
// 电梯地下室等场景手机信号不好,则需要多次尝试,如果多次尝试都发
// 送不出去,则就需要捕获异常再重新抛出,其次如果不是网络差导致的
// 错误,捕获后也要重新抛出。

void _SeedMsg(const string& s)
{
	if (rand() % 3 == 0)
	{
		throw HttpException("网络不稳定,发送失败", 102, "put");
	}
	else if (rand() % 7 == 0)
	{
		throw HttpException("你已经不是对象的好友,发送失败", 103, "put");
	}
	else
	{
		cout << "发送成功" << endl;
	}
}

void SendMsg(const string& s)
{
	// 发送消息失败,则再重试3次
	for (size_t i = 0; i < 4; i++)
	{
		try
		{
			_SeedMsg(s);
			break;
		}
		catch (const Exception& e)
		{
			// 捕获异常,if中是102号错误,网络不稳定,则重新发送
			// 捕获异常,else中不是102号错误,则将异常重新抛出
			if (e.getid() == 102)
			{
				// 重试三次以后否失败了,则说明网络太差了,重新抛出异常
				if (i == 3)
					throw;

				cout << "开始第" << i + 1 << "重试" << endl;
			}
			else
			{
				throw;
			}
		}
	}
}

int main()
{
	srand(time(0));
	string str;
	while (cin >> str)
	{
		try
		{
			SendMsg(str);
		}
		catch (const Exception& e)
		{
			cout << e.what() << endl << endl;
		}		
        catch (...)
		{
			cout << "Unkown Exception" << endl;
        }
    }

    return 0;
}

5 异常安全问题

异常抛出后,后面的代码就不再执行,前面申请了资源(内存、锁等),后⾯进行释放,但是中间可
能会抛异常就会导致资源没有释放,这里由于异常就引发了资源泄漏,产生安全性的问题。中间我
们需要捕获异常,释放资源后面再重新抛出,当然后面智能指针章节讲的RAII方式解决这种问题是
更好的。
其次析构函数中,如果抛出异常也要谨慎处理,比如析构函数要释放10个资源,释放到第5个时抛
出异常,则也需要捕获处理,否则后面的5个资源就没释放,也资源泄漏了。
 
double Divide(int a, int b) { 
	// 当b == 0时抛出异常 
	if (b == 0) 
	{ 
		throw "Division by zero condition!"; 
	}
	return (double)a / (double)b; 
}
void Func()
{
	// 这里可以看到如果发生除0错误抛出异常,另外下面的array没有得到释放。
	// 所以这里捕获异常后并不处理异常,异常还是交给外层处理,这里捕获了再
	// 重新抛出去。
	int* array = new int[10];
	try
	{
		int len, time;
		cin >> len >> time;
		cout << Divide(len, time) << endl;
	}
	catch (...)      //不管什么异常都可以接到,先把内存释放了,在把这个异常抛出去
	{
		cout << "delete []" << array << endl;
		delete[] array;

		throw;
	}

	cout << "delete []" << array << endl;
	delete[] array;
}
int main()
{
	int i = 0;
	cout << noexcept(Divide(1, 2)) << endl;
	cout << noexcept(Divide(1, 0)) << endl;
	cout << noexcept(++i) << endl;

	try
	{
		Func();
	}
	catch (const string& errmsg)
	{
		cout << errmsg << endl;
	}
	catch (const exception& e)
	{
		cout << e.what() << endl;
	}
	catch (...)
	{
		cout << "Unkown Exception" << endl;
	}
	return 0;
}

 6 异常规范

C++11中函数参数列表后面加 noexcept表示不会抛出异常,啥都不加表示可能会抛出异常。
编译器并不会在编译时检查noexcept,也就是说如果一个函数用noexcept修饰了,但是同时又包
含了throw语句或者调用的函数可能会抛出异常,编译器还是会顺利编译通过的(有些编译器可能会
报个警告)。但是一个声明了noexcept的函数抛出了异常,程序会调用 terminate 终止程序。
noexcept(expression)还可以作为一个运算符去检测一个表达式是否会抛出异常,可能会则返回
false,不会就返回true。
代码见上述例子中!

相关文章:

  • java实体类常用参数验证
  • DepthAI ROS 安装与使用教程
  • 从传统 CLI 到自动化:网管协议( SNMP / NETCONF / RESTCONF)与 YANG
  • Java SE(2)——运算符
  • 艾尔登法环Steam不同账号存档互通方法与替换工具分享
  • nginx入门,部署静态资源,反向代理,负载均衡使用
  • 【基于LangChain的千问大模型工具调用】 Function CallingTool Calling简易示例
  • SCS翠鸟认证是什么,SCS翠鸟认证的意义?对企业发展好处
  • NO.88十六届蓝桥杯备战|动态规划-多重背包|摆花(C++)
  • SpringBoot 基础知识,HTTP 概述
  • 从递归入手一维动态规划
  • Java的内存模型
  • 高等数学同步测试卷 同济7版 试卷部分 上 做题记录 第二章导数与微分同步测试卷A卷
  • Java Lambda与方法引用:函数式编程的颠覆性实践
  • Soybean Admin 配置vite兼容低版本浏览器、安卓电视浏览器(飞视浏览器)
  • “pip“ is not recognized(pip无法被识别)
  • VBA即用型代码手册:书签Bookmarks
  • ARCGIS PRO 在已建工程地图中添加在线地图
  • Soybean Admin移除git-hooks永久关闭git校验
  • 【算法】——一键解决动态规划