一文带你真正搞懂C++异常处理机制

🤖个人主页晚风相伴-优快云博客

💖如果觉得内容对你有帮助的话,还请给博主一键三连(点赞💜收藏🧡关注💚)吧

🙏如果内容有误的话,还望指出,谢谢!!!

目录

对比C语言处理错误的方式

C++异常的概念

异常的使用和规范

异常的抛出和匹配原则

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

异常的重新抛出

异常中需要注意的点

异常规范

异常的优缺点比较

优点

缺点


😎对比C语言处理错误的方式

C语言的错误处理方式

  1. 直接终止程序,如assert,如果发生内存错误,除0错误时就会终止程序。缺陷:用户难以接受。
  2. 返回错误码,如系统的很多库的接口函数都是通过把错误码放到errno中来表示错误。缺陷:需要我们自己根据错误码去查找对应的错误信息。

在实际中C语言基本都是使用返回错误码的方式来处理错误,部分情况下会使用直接终止程序的方式处理非常严重的错误。

👍C++异常的概念

异常是一种处理错误的方式,当一个函数发现自己无法处理的错误时就可以抛出异常,让函数直接或间接的调用来处理这个错误。

处理异常的关键字

  • throw:当异常出现时,会通过throw关键字将异常抛出。
  • catch:捕获并处理被throw抛出的异常,可以有多个catch进行捕获。
  • try:try块中的代码标识将被激活的特定异常,和catch搭配使用。

如果有一个块抛出一个异常,捕获异常的方法会使用try和catch关键字。try块中放置可能抛出异常的代码,try块中的代码被称为保护代码。

try/catch语句的使用方式如下所示

try
{
// 保护的标识代码
}
catch( ExceptionName e1 )//捕获异常
{
// catch块 处理异常
}
catch( ExceptionName e2 )//捕获异常
{
// catch块 处理异常
}
catch( ExceptionName eN )//捕获异常
{
// catch块 处理异常
}

例如

一个除0错误抛出异常的演示代码

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

void Test()
{
	int a, b;
	cin >> a >> b;
	cout << Division(a, b) << endl;
}

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

当发生除0错误时会抛出异常

🔥异常的使用和规范

👀异常的抛出和匹配原则

1、异常是通过抛出对象而引发的,该对象的类型决定了应该激活哪个catch块的处理代码。

在上述代码中就会激活string类型的catch块

✨2、被选中的处理代码是调用链中与该对象类型匹配且离抛出异常位置最近的那一个。

3、抛出异常后会生成一个异常对象的拷贝,因为抛出的异常对象可能是一个临时对象,所以会生成一个拷贝对象,这个拷贝的临时对象会在被catch以后销毁。

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

double Division(int a, int b)
{
	//当b == 0时抛异常
	if (b == 0)
	{
		Exception e("除0错误", 1);
		throw e;//会将拷贝对象抛给catch
	}
	else
		return ((double)a / (double)b);
}

✨4、catch(...)可以捕获任意类型的异常,缺陷就是并不知道异常错误是什么,一般是用来表示代码中的未知错误并且是放在众多catch块的最后保证程序在循环中不退出。

 

✨5、在实际中抛出和捕获的匹配原则有个例外,并不都是类型完全匹配,可以抛出派生类的对象,并使用基类捕获。

// 服务器开发中通常使用的异常继承体系
// 模拟服务器出现异常的情况
class Exception
{
public:
	Exception(const string& errmsg, int id)
		:_errmsg(errmsg)
		, _id(id)
	{}
	virtual string what() const
	{
		return _errmsg;
	}
protected:
	string _errmsg;
	int _id;
};

//处理sql异常
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;
	}
};

//处理http服务器异常
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("权限不足", 300, "select * from name = '张三'");
	}
}

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");
	}
	else if (rand() % 4 == 0)
	{
		throw HttpServerException("权限不足", 101, "post");
	}
	CacheMgr();
}

int main()
{
	while (1)
	{
		Sleep(1000);
		try {
			HttpServer();
		}
			catch (const Exception& e)
		{
			// 多态
			cout << e.what() << endl;
		}
		catch (...)//处理未知错误,保证程序不退出
		{
			cout << "未知错误" << endl;
		}
	}
	return 0;
}

 💯在函数调用链中异常栈展开匹配原则

  1. 首先检查throw本身是否在try块内部,如果在,则查找匹配的catch块,如果有匹配的catch块,则调到相匹配的catch块中进行处理。
  2. 没有匹配的catch则退出当前函数栈,继续在调用函数的栈中进行查找匹配的catch。
  3. 如果到达main函数的栈,依旧没有匹配的,则终止程序。

上述这个沿着调用链查找匹配的catch子句的过程称为栈展开。因此在实际中我们最后都要加上一个catch(...)捕获任意类型的异常,否则当前有异常没有捕获程序就会终止。程序在找到匹配的catch子句并处理完后,会沿着catch子句后面继续执行。

👉异常的重新抛出

有可能单个的catch不能完全处理一个异常,在进行一些校正处理以后,希望再交给更外层的调用链函数来处理,catch则可以通过重新抛出将异常传递给更上层的函数进行处理。

例如你在微信发消息时,在遇到网络不好的情况下,它并不是立马给你抛出个异常叫你检查一下网络,而是先在那里转圈圈,转圈圈表示它还在重试发送看看能不能发送成功,如果重试发送到一定值还没有成功,再给你抛出个网络不好的异常。

模拟网络不好重发消息的情况 

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 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 SeedMsg(const string& s)
{
	// 出现网络错误重试发送5次
	srand(time(0));
	if (rand() % 3 == 0)
	{
		throw HttpServerException("网络错误", 100, "get");
	}
	else if (rand() % 4 == 0)
	{
		throw HttpServerException("权限不足", 101, "post");
	}

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

void HttpServer()
{
	// 出现网络错误重试5次
	string str = "可以做我女朋友吗?";
	int n = 5;
	while (n--)
	{
		try
		{
			SeedMsg(str);
			// 没有发生异常
			break;
		}
		catch (const Exception& e)
		{
			// 网络错误且在重试的5次内
			if (e.getid() == 100 && n > 0)
			{
				continue;
			}
			else
			{
				throw e; // 重新抛出
			}
		}
	}
}

int main()
{
	while (1)
	{
		Sleep(1000);
		try {
			HttpServer();
		}
		catch (const Exception& e)
		{
			cout << e.what() << endl;
		}
		catch (...)
		{
			cout << "未知错误" << endl;
		}
	}
	return 0;
}

🔥异常中需要注意的点

  • 不要在构造函数中抛出异常,否则可能导致对象不完整或没有完全初始化。
  • 不要在析构函数内抛出异常,否则可能导致资源泄露。
  • 在new和delete之间或者在lock和unlock之间抛出异常要慎重,容易导致内存泄漏等问题。

💨异常规范

  1. 在函数后面接throw(类型),列出这个函数可能抛出的所有异常类型。
  2. 函数的后面接throw(),表示这个函数不抛异常。
  3. 若无异常接口声明,则此函数可以抛出任何类型的异常。
// C++98语法支持
// 这里表示这个函数会抛出A/B/C/D中的某种类型的异常
void fun() throw(A,B,C,D);
// 这里表示这个函数只会抛出bad_alloc的异常
void* operator new (std::size_t size) throw (std::bad_alloc);
// 这里表示这个函数不会抛出异常
void* operator delete (std::size_t size, void* ptr) throw();

// C++11 中新增的noexcept,表示不会抛异常
thread() noexcept;
thread (thread&& x) noexcept;

当然在C++标准库中提供了一系列标准的异常,定义在  <exception> 中,大家可以自行去查阅。但是实际在很多公司中都会自定义自己的异常体系进行规范的异常管理。

🤓异常的优缺点比较

优点

  1. 自定义异常对象定义好了,相比错误码的方式可以清晰准确的展示出错误的各种信息,甚至可以包含堆栈调用的信息,这样可以帮助更好的定位程序的bug。
  2. 很多的第三方库都包含异常,比如boost、gtest、gmock等等常用的库,那么我们使用它们也需要使用异常。
  3. 部分函数使用异常更好处理,比如构造函数没有返回值,不方便使用错误码方式处理。比如T& operator这样的函数,如果pos越界了只能使用异常或者终止程序处理,没办法通过返回值表示错误。
  4. 支持从多个层次传递错误信息,异常可以在函数之间进行传递,这意味着当一个函数发生错误时,它可以选择将错误信息传递给调用它的函数,直到错误被处理为止。

缺点

  1. 异常会导致程序的执行流乱跳,并且非常的混乱,并且是运行时出错抛异常就会乱跳。这会导致我们跟踪调试时以及分析程序时,比较困难。
  2. 异常会有一些性能的开销。当然在现代硬件速度很快的情况下,这个影响基本忽略不计。
  3. C++没有垃圾回收机制,资源需要自己管理。有了异常非常容易导致内存泄漏、死锁等异常安全问题。这个需要使用RAII来处理资源的管理问题。学习成本较高。
  4. C++标准库的异常体系定义得不好,导致大家各自定义各自的异常体系,非常的混乱。

总结:异常总体而言,利大于弊,所以工程中我们还是鼓励使用异常的。另外所有的语言基本都是
用异常处理错误,这也可以看出这是大势所趋。

 

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值