0
点赞
收藏
分享

微信扫一扫

python 爱心代码

JakietYu 04-03 20:00 阅读 2

目录

一,背景

1.1 C语言处理错误的方式

1.2 C++异常概念

二,异常的使用

2.1 异常的简单使用

2.2 异常的匹配原则

2.3 异常抛对象

 2.4 异常的重新抛出

 2.5 异常安全

三,自定义异常体系

四,异常优缺点

4.1 优点

4.2 缺点

一,背景

1.1 C语言处理错误的方式

在C语言中处理错误的基本方式有两种:

1.2 C++异常概念

异常是一种处理错误的方式,当一个函数发现自己无法处理的错误时就可以抛出异常,让函数的直接或间接地调用者处理这个错误。主要包括下面三个关键字:

①throw:当问题出现时,通过这个关键字“抛出”具体地错误信息

②catch:通过catch关键字捕获throw抛出地异常信息,通过一个字符串或类接收,然后根据信息针对处理

③try:try和catch配套使用,throw在try中使用,try后面一般跟着一个或多个catch捕获

二,异常的使用

2.1 异常的简单使用

//throw:当问题出现时,程序会抛出一个异常
//catch:捕获异常
//try:包含多个catch
double Division1(int a, int b)
{
	// 当b == 0时抛出异常
	if (b == 0)
		throw "Division by zero condition!";
	else
		return ((double)a / (double)b);
}

void Func1()
{
	//如果Func里面也有捕获,出异常的时候如果Func里有和throw抛出内容类型一样的就跳到Func里的,如果没有匹配类型,就继续往下找直到跳到匹配类型的catch
	try
	{
		int len, time;
		cin >> len >> time;
		cout << Division1(len, time) << endl;
	}
	catch (int errid)
	{
		cout << errid << endl;
	}
	cout << "Func1() end" << endl;
}

void main()
{
	while (1)
	{
		try
		{
			Func1();
		}
		//没有异常的时候直接跳过catch
		catch (const char* errmsg)
		{
			//如果throw了,直接跳到离throw位置最近的catch
			cout << errmsg << endl;
		}
		允许多个catch,对于throw的不同类型匹配不同的catch,但是多个catch不允许有相同传参类型的catch
		catch (int errid)
		{
			cout << errid << endl;
		}
		catch (char errmsg)
		{
			cout << errmsg << endl;
		}

		//如果throw的内容没有匹配类型的catch,会直接报错,直接终止程序
		catch (...) //捕获任意类型的异常 -- 防止出现未捕获异常时直接报错,程序终止
		{
			cout << "未知异常" << endl;
		}
	}
}

 

2.2 异常的匹配原则

异常的抛出和匹配原则:

在函数调用链中异常栈匹配原则:

2.3 异常抛对象

class Exception
{
public:
	Exception(const string& errmsg, int id)
		:_errmsg(errmsg)
		, _errid(id)
	{}
	virtual string what() const
	{
		return _errmsg;
	}

	int GetErrid()
	{
		return _errid;
	}

	int getid()const
	{
		return _errid;
	}
protected:
	string _errmsg;
	int _errid;
};

double Division2(int a, int b)
{
	//当b == 0时抛出异常
	if (b == 0)
	{
		/*Exception e("除0错误", a);
		throw e;*/
		throw Exception("除0错误", a);
	}
	else
	{
		return ((double)a / (double)b);
	}
}

void Func2()
{
	int len, time;
	cin >> len >> time;
	cout << Division2(len, time) << endl;
}

//1,抛异常可以抛任意类型对象
//2,捕获时,要求类型匹配

void main2()
{
	while (1)
	{
		try
		{
			Func2();
		}
		catch (const Exception& e)
		{
			cout << e.what() << endl;
		}
		catch (...) // 捕获任意类型的异常 -- 防止出现未捕获异常时,程序终止
		{
			cout << "未知异常" << endl;
		}
	}
}

 2.4 异常的重新抛出

有时候抛异常了,但是不是只要有异常了就报错,比如我们发送消息的时候,第一次发送失败不是直接就报错,而是再多发几次,多发几次都失败后才报错,如下代码:

void SeedMsg(const string& s)
{
	// 要求出现网络错误重试三次
	srand(time(0));
	if (rand() % 3 == 0) //模拟服务出错,偶然情况下满足这个if,达到模拟错误的效果
	{
		throw HttpServerException("网络错误", 100, "get");
	}
	else if (rand() % 4 == 0)
	{
		throw HttpServerException("权限不足", 101, "post");
	}

	cout << "发送成功:" << s << endl;
}

void HttpServer1()
{
	// 要求出现网络错误,重试3次
	string str = "今晚一起看电影怎么样?";
	int n = 3;
	while (n--)
	{
		try
		{
			SeedMsg(str);

			// 没有发生异常,跳出循环
			break;
		}
		catch (const Exception& e)
		{
			// 网络错误 && 重试3次内
			if (e.getid() == 100 && n > 0)
			{
				continue;//这是网络错误后继续调SeedMsg,然后继续网络错误重试
			}
			else
			{
				throw e; // 超过三次网络错误直接,重新抛出
			}
		}
	}
}

void main()
{
	while (1)
	{
		//this_thread::sleep_for(chrono::seconds(1));
		Sleep(1000);

		try
		{
			HttpServer();
		}
		catch (const Exception& e) // 这里捕获父类对象就可以
		{
			// 多态
			cout << e.what() << endl;
			// 记录日志
		}
		catch (...)
		{
			cout << "Unkown Exception" << endl;
		}
	}
}

 2.5 异常安全

①最好不要在构造函数中抛出异常,否则可能导致对象不完整或没有初始化完成

②最好不要在析构函数内抛出异常,否则可能导致资源泄漏

③C++中异常经常会导致资源泄漏问题,比如在new和delete中抛出了异常,导致内存泄漏,或者在lock和unlock抛异常导致死锁,C++经常使用RAII来解决上面的问题,关于RAII我们到智能指针进行讲解

double Division(int a, int b)
{
	// 当b == 0时抛出异常
	if (b == 0)
	{
		throw "Division by zero condition!";
	}
	return (double)a / (double)b;
}

void Func3()
{
	// 这里可以看到如果发生除0错误抛出异常,另外下面的array没有得到释放。
	// 所以这里捕获异常后并不处理异常,异常还是交给外面处理,这里捕获了再
	// 重新抛出去。

	// 隐患,第一个成功,第二个失败
	//可以解决,但是很麻烦,这样的问题一般是用智能指针解决
	int* array1 = new int[10];
	int* array2 = new int[10];


	int len, time;
	cin >> len >> time;

	try
	{
		cout << Division(len, time) << endl;
	}
	catch (...)
	{
		cout << "delete []" << array1 << endl;
		delete[] array1;

		cout << "delete []" << array1 << endl;
		delete[] array2;

		throw; // 捕获什么抛出什么
	}

	cout << "delete []" << array1 << endl;
	delete[] array1;

	cout << "delete []" << array2 << endl;
	delete[] array2;
}

void main5()
{
	try
	{
		Func3();
	}
	catch (const char* errmsg)
	{
		cout << errmsg << endl;
	}
}

三,自定义异常体系

C++库给我们提供了一系列标准的异常,定义在std::exception中。在实际中我们可以去继承exception类实现自己的异常类。但是实际上很多公司有一套属于自己的异常继承体系,因为C++标准库给的并不好用。

很多公司都会自定义自己的异常体系进行规范的异常管理,因为一个项目中如果大家都随意抛异常,那么外层的调用者基本没法玩了。

下面就是简单模拟服务器开发中的异常体系:

class Exception
{
public:
	Exception(const string& errmsg, int id)
		:_errmsg(errmsg)
		, _errid(id)
	{}
	virtual string what() const
	{
		return _errmsg;
	}

	int GetErrid()
	{
		return _errid;
	}

	int getid()const
	{
		return _errid;
	}
protected:
	string _errmsg;
	int _errid;
};

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;
	}
protected:
	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;
	}

protected:
	 //stack<string> _stPath;
};

class HttpServerException : public Exception//网络服务错误
{
public:
	HttpServerException(const string& errmsg, int id, const string& type)
		:Exception(errmsg, id)
		, _type(type)
	{}

	virtual string what() const
	{
		string str = "HttpServerException:";
		str += _type;
		str += ":";
		str += _errmsg;

		return str;
	}

private:
	const string _type;
};

void SQLMgr()//数据库
{
	srand(time(0));
	if (rand() % 7 == 0)
	{
		throw SqlException("权限不足", 100, "select * from name = '张三'");
	}

	cout << "本次请求成功" << endl;//如果都没有异常直接就打印这个,这里只是用来演示
}

void CacheMgr() //缓存
{
	srand(time(0));
	if (rand() % 5 == 0)
	{
		throw CacheException("权限不足", 200);
	}
	else if (rand() % 6 == 0)
	{
		throw CacheException("数据不存在", 201);
	}

	SQLMgr();
}

void HttpServer() //网络服务
{
	// 模拟出错
	srand(time(0));

	if (rand() % 3 == 0)
	{
		//throw HttpServerException("请求资源不存在", 100, "get");
		throw HttpServerException("网络错误", 100, "get");
	}
	else if (rand() % 4 == 0)
	{
		throw HttpServerException("权限不足", 101, "post");
	}

	CacheMgr();//重试,根据重试次数来抛对应组的异常
}

void SeedMsg(const string& s)
{
	// 要求出现网络错误重试三次
	srand(time(0));
	if (rand() % 3 == 0) //模拟服务出错,偶然情况下满足这个if,达到模拟错误的效果
	{
		throw HttpServerException("网络错误", 100, "get");
	}
	else if (rand() % 4 == 0)
	{
		throw HttpServerException("权限不足", 101, "post");
	}

	cout << "发送成功:" << s << endl;
}

void main()
{
	while (1)
	{
		Sleep(1000);
		try
		{
			HttpServer();
		}
		catch (const Exception& e)
		{
			//多态
			cout << e.what() << endl;
		}
		catch (...)
		{
			cout << "Unknow Exception" << endl;
		}
	}
}

四,异常优缺点

4.1 优点

①异常对象定义好了,相比错误码的方式我们可以清晰准确地显示出错误的各种信息,甚至可以包含堆栈的调用信息,这样可以更好地定位程序地bug

②很多地第三方库都包含异常,比如boost,gtest,gmock等等常用地库,那么我们使用它们的时候也需要使用库

③部分函数使用异常可以更好地处理,比如构造函数没有返回值,不方便使用错误码的方式处理。比如T& operator这样的函数,如果pos越界了只能使用异常或终止程序处理,没办法通过返回值表示错误

4.2 缺点

①异常会使我们的程序执行流乱跳,一旦没使用好就会变得非常混乱,并且是运行时乱跳,所以可能会跳过我们调试的断点,导致我们跟踪调试以及分析程序时,比较困难

②异常会有一些性能的开销。当然现代硬件速度已经很快,现在暂时不考虑

③C++没有java的垃圾回收机制,资源需要自己管理,异常会导致资源泄漏的情况经常发送,还有死锁等安全问题。这个我们到智能指针再说

④C++标准库的异常体系定义得不好,导致大家自定义各自得异常体系,非常混乱

总结:异常总体而言,是利大于弊得,所以工程中我们鼓励使用异常,OO得语言基本都是用异常处理错误,这也是大势所趋。

举报

相关推荐

0 条评论