C++异常

前言

本文讲异常

1. C语言传统的处理错误的方式

C语言处理错误的方式主要是assert断言和错误码errno

2. C++异常概念

C++异常主要是通过三个关键字来实现的
第一个是try,它主要是看你对什么进行抛异常
第二个是throw,主要是抛出异常
第三个就是catch,主要是对throw抛出的异常进行捕获

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

void Func()
{
	int len, time;
	cin >> len >> time;
	cout << Division(len, time) << endl;
	cout<<12<<endl;
}

int main()
{
	try 
	{
		Func();
	}
	catch (const char* errmsg)
	{
	cout << errmsg << endl;
	}
	return 0;
}

看这个程序,第二个参数输入0就会抛异常
在这里插入图片描述
throw 抛出异常之后,就会从当前函数开始,有没有捕获,就是检测catch,
如果本个函数函数没有,那就会跳到下一个函数检测catch,直到main函数,注意,这个过程,只是检测有没有catch,不会去运行这些程序

然后就是throw的东西和catch接收的东西,类型应该是一样的,是严格对应的

catch (const string&s)
{
cout << s << endl;
}

在这里插入图片描述
就算可以强制类型转换的也不行

所以说捕获到异常,就相当于直接跳到catch了

catch (const char* errmsg)
{
cout << errmsg << endl;
}
cout << 12345 << endl;

在这里插入图片描述
然后就是捕获到了异常,就会跳到catch,然后catch后面的程序还是会正常执行的

然后就是抛出了异常,写了try,写了throw就一定要catch
而且try和catch一定是紧挨着的,try后面一定要跟着catch

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

void Func()
{
	int len, time;
	cin >> len >> time;
	try
	{
		cout << Division(len, time) << endl;
	}
	catch (const char* errmsg)
	{
		cout << 12345 << endl;
		cout << errmsg << endl;
	}
}

int main()
{
	try 
	{
		Func();
	}
	catch (const char* errmsg)
	{
	cout << errmsg << endl;
	}
	return 0;
}

在这里插入图片描述
一次throw只会对应一次catch,只会执行一个catch,而且这个catch肯定是最近的catch,就是按照函数递归的顺序找到的catch

try 
{
	Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch(int a)
{
	cout << a << endl;
}

然后就是一个try后面可以跟着很多个catch,为了防止throw出其他类型,没有接收到

double Division(int a, int b)
{
	// 当b == 0时抛出异常
	if (b == 0)
		throw 11;
	else
		return ((double)a / (double)b);
}

void Func()
{
	int len, time;
	cin >> len >> time;
	try
	{
		cout << Division(len, time) << endl;
	}
	catch (const char* errmsg)
	{
		cout << 12345 << endl;
		cout << errmsg << endl;
	}
}

int main()
{
	try 
	{
		Func();
	}
	catch (const char* errmsg)
	{
	cout << errmsg << endl;
	}
	catch(...)
	{
		cout << "unkown exception" << endl;
	}
	return 0;
}

在这里插入图片描述
然后就是catch的参数类型可以是三个点,这个就表示接受throw返回的任意类型
但这个一般放在后面,因为不知道是什么类型的嘛

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

void Func()
{
	int len, time;
	cin >> len >> time;
	try
	{
		cout << Division(len, time) << endl;
	}
	catch (const char* errmsg)
	{
		cout << 12345 << endl;
		cout << errmsg << endl;
	}
}

int main()
{
	try 
	{
		Func();
	}
	catch (const char* errmsg)
	{
	cout << errmsg << endl;
	}
	catch(...)
	{
		cout << "unkown exception" << endl;
	}
	return 0;
}

然后就是throw 抛出对象"Division by zero condition!",是要先对"Division by zero condition!"进行拷贝,拷贝出一个对象,然后对象在赋值给const char* errmsg

3. 抛异常与派生类,基类

可以抛出的派生类对象,
使用基类捕获

// 服务器开发中通常使用的异常继承体系
class Exception
{
public:
	Exception(const string& errmsg, int id)
		:_errmsg(errmsg)
		, _id(id)
	{}
	virtual string what() const
	{
		return _errmsg;
	}
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 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 = '张三'");
	}
	//throw "xxxxxx";
}
void CacheMgr()
{
	srand(time(0));
	if (rand() % 5 == 0)
	{
		throw CacheException("权限不足", 100);
	}
	else if (rand() % 6 == 0)
	{
		throw CacheException("数据不存在", 101);
	}
	SQLMgr();
}
void HttpServer()
{
	// ...
	srand(time(0));
	if (rand() % 3 == 0)
	{
		throw HttpServerException("请求资源不存在", 100, "get");
	}
	else if (rand() % 4 == 0)
	{
		throw HttpServerException("权限不足", 101, "post");
	}
	CacheMgr();
}
#include<chrono>
#include <thread>         
using namespace std;
int main()
{
	while (1)
	{
		this_thread::sleep_for(chrono::seconds(1));
		try {
			HttpServer();
		}
		catch (const Exception& e) // 这里捕获父类对象就可以
		{
			// 多态
			cout << e.what() << endl;
		}
		catch (...)
		{
			cout << "Unkown Exception" << endl;
		}
	}
	return 0;
}

在这里插入图片描述
看这个程序,就是用的基类来接收抛异常,不同的派生类,就会打印出不同的东西

void CacheMgr()
{
	if (rand() % 2 == 0)
	{
		throw CacheException("网络不佳", 100);
	}
	else if (rand() % 3 == 0)
	{
		throw CacheException("对方已删除你的好友", 101);
	}
	throw CacheException("发送成功", 103);
}
void HttpServer()
{
	//网络不佳,就重新发送三次
	for (int i = 0; i < 4; i++)
	{
		try
		{
			CacheMgr();
		}
		catch (const Exception& e)
		{
			if (e.GetId() == 100)
			{
				if (i == 3)
				{
					cout << "发送失败" << endl;
					break;
				}
				cout << "网络不佳,开始第" << i + 1 << "次发送" << endl;
			}
			else if(e.GetId() == 101)
			{
				//break;//break跳出的是catch,所以不用break
				throw e;
			}
			else
			{
				throw e;
			}
		}
	}
}
#include<chrono>
#include <thread>         
using namespace std;
int main()
{
	srand(time(0));
	int n = 10;
	while (1)
	{
		this_thread::sleep_for(chrono::seconds(1));
		try {
			HttpServer();
		}
		catch (const Exception& e)
		{
			cout << e.what()<< endl;
		}
		cout << endl;
	}
	return 0;
}

在这里插入图片描述
如上,这个程序就能很好的模拟出我们发送消息的时候的场景

4. 异常的重新抛出

double Division(int a, int b)
{
	// 当b == 0时抛出异常
	if (b == 0)
	{
		throw "Division by zero condition!";
	}
	return (double)a / (double)b;
}
void Func()
{
	int* array = new int[10];
	try {
		int len, time;
		cin >> len >> time;
		cout << Division(len, time) << endl;
	}
	catch (...)
	{
		cout << "delete []" << array << endl;
		delete[] array;
		throw;
	}
	// ...
	cout << "delete []" << array << endl;
	delete[] array;
}
int main()
{
	try
	{
		Func();
	}
	catch (const char* errmsg)
	{
		cout << errmsg << endl;
	}
	return 0;
}

在这里插入图片描述
这里可以看到如果发生除0错误抛出异常,另外下面的array没有得到释放。
所以这里捕获异常后并不处理异常,异常还是交给外面处理,这里捕获了再重新抛出去。

这里的意思就是如果抛异常了,先释放空间,在抛异常给外面,因为一个throw只能对应一个catch嘛,在catch里面再写throw,就可以传递给其他的catch了,注意不是还传递给当前的catch哈

catch (const char*arr)
{
	cout << "delete []" << array << endl;
	delete[] array;
	throw arr;
}

还可以这样写,捕获arr,再抛出arr
当然

catch (...)
	{
		cout << "delete []" << array << endl;
		delete[] array;
		throw;
	}

这样写也是那个意思,捕获arr,再抛出arr,只不过这样写更简便,三个点的意思就相当于auto的意思,万能的接受,再来个空白的throw,就相当于把这个auto的抛出去了

catch (const char* arr)
{
	cout << "delete []" << array << endl;
	delete[] array;
	throw;
}

所以这样写也可以

int* array1 = new int[10];
int* array2 = new int[10];
delete array1;
delete array2;

注意new本身也会抛异常的,我们以前说过的,new也会抛异常
new如果失败了,就会抛异常,array1抛异常还好说,反正开辟失败了没事,array2 还没开始开辟空间
如果array2 抛异常了就不好说了,因为说明array1已经开辟好了,开辟成功了,那么它的空间就不好释放了,因为无法把array1的地址抛给throw
,所以后面写的delete array1;就没有什么用了,而且还真的不好处理,
所以这个时候就可以用智能指针去处理了,这个就很好处理

5 异常的利与弊

这里有要说明的几点
第一就是不要再构造和析构函数中抛异常,因为可能会导致构造和析构不完整
函数的后面接throw(),表示函数不抛异常。
C++11 中新增的noexcept,表示不会抛异常
函数后面加上noexcept也表示不会抛异常
在这里插入图片描述
在这里插入图片描述
C++标准库中有很多throw的接口,有的越界,有的开辟空间失败,反正有很多很多,因为C++标准库的很多函数都加了抛异常的,所以要有对应的throw接口才行

// 这里表示这个函数只会抛出bad_alloc的异常
void* operator new (std::size_t size) throw (std::bad_alloc);

比如这个bad_alloc就是一种throw类型

// 这里表示这个函数不会抛出异常
void* operator delete (std::size_t size, void* ptr) throw();
// C++11 中新增的noexcept,表示不会抛异常
thread() noexcept;
thread (thread&& x) noexcept;

总结

下一节讲智能指针

  • 12
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值