【C++练级之路】【Lv.24】异常

发布于:2024-06-05 ⋅ 阅读:(40) ⋅ 点赞:(0)



快乐的流畅:个人主页


个人专栏:《算法神殿》《数据结构世界》《进击的C++》

远方有一堆篝火,在为久候之人燃烧!

引言

C语言处理错误的方式:

  1. 返回错误码,缺陷:需要程序员自己查找错误信息。
  2. 终止程序(如assert),缺陷:用户难以接受。

ps:assert在debug下起作用,在release下不起作用。

一、异常的概念及定义

1.1 异常的概念

鉴于C语言中处理错误的方式不够理想和方便,C++推出了自己处理错误的方式——异常。当一个函数遇到无法处理的错误时,会抛出异常,让函数的调用者来处理

1.2 异常的定义

先看看以下代码:

void func()
{
	throw "error";
}

void test()
{
	try
	{
		func();
	}
	catch (const char* str)
	{
		cout << str << endl;
	}
	catch (...)
	{
		cout << "未知异常" << endl;
	}
}
  • throw:用于抛异常
  • try:用于包围可能会抛出异常的代码
  • catch:用于捕获异常

ps:try语句可以接多条catch语句,用于捕获不同类型的异常。
ps:异常与对应类型的catch语句相匹配。
ps:catch (…)可用于捕获任意类型的异常,防止未知异常导致程序终止。

二、异常的使用

2.1 异常的栈展开匹配

double Division(int len, int time)
{
	if (time == 0)
	{
		throw "除零错误";
	}
	else
	{
		return (double)len / time;
	}
}

void func()
{
	throw 1;
}

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

int main()
{
	try
	{
		Func();
	}
	catch (const char* str)
	{
		cout << str << endl;
	}
	catch (...)
	{
		cout << "未知异常" << endl;
	}
}
  1. 先检查throw是否在try语句块中,如果在,则匹配相应的catch语句。
  2. 如果匹配不到或者不在,则退出当前函数栈,继续在调用函数的栈中进行查找匹配的catch语句。
  3. 如果到达main函数的栈,依旧没有匹配的,则终止程序。
  4. 如果匹配到相应的catch语句并处理后,会继续执行catch后面的内容。

ps:在异常被抛出时,会创建一个异常对象的拷贝(或移动)。这个拷贝(或移动的结果)是用于在调用栈中向上传递的,直到找到匹配的catch块。这是为了确保在抛出点之后,原始对象的状态改变不会影响已经抛出的异常对象。

2.2 异常的重新抛出

有时你可能希望在catch块中捕获异常后,不立即处理它,而是选择重新抛出(rethrow)它,以便让更上层的代码有机会处理它。

请看看以下代码:

double Division(int len, int time)
{
	if (time == 0)
	{
		throw "除零错误";
	}
	else
	{
		return (double)len / time;
	}
}

void Func()
{
	int* p = new int[10];
	try
	{
		int len, time;
		cin >> len >> time;
		cout << Division(len, time) << endl;
	}
	catch (...)
	{
		delete[] p;
		throw;//捕到什么抛什么
	}
	delete[] p;
}

int main()
{
	try
	{
		Func();
	}
	catch (const char* str)
	{
		cout << str << endl;
	}
}
  • 重新抛出:throw;

在上述场景中,因为可能抛异常导致动态开辟的空间不能释放,所以就需要在catch语句中先释放空间,再将异常重新抛出。

2.3 异常安全

  • 构造函数完成对象的构造和初始化,最好不要在构造函数中抛出异常,否则可能导致对象不完整或没有完全初始化。
  • 析构函数主要完成资源的清理,最好不要在析构函数内抛出异常,否则可能导致资源泄漏(内存泄漏、句柄未关闭等)

C++中异常会频繁导致资源泄漏的问题,比如在new和delete中抛出了异常,导致内存泄漏,在lock和unlock之间抛出了异常导致死锁,C++经常使用RAII来解决以上问题(智能指针章节)。

2.4 异常规范

// 这里表示这个函数会抛出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;
  • 函数的后面接throw(类型),列出这个函数可能抛掷的所有异常类型。
  • 函数的后面接throw(),表示函数不抛异常。
  • C++11新增关键字noexcept,更加简洁地表示不会抛异常

最重要的是,这些只是一个期望规范,编译器不会强制检查和报错,哪怕写的并不对(甚至可以不写)。

三、自定义异常体系

实际上,异常的抛出和捕获,有一种特例不需要类型相对应。那就是抛出派生类对象,用基类来捕获(这也是实际中非常实用的做法)。

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();
}

int main()
{
	while (1)
	{
		sleep(100);
		try
		{
			HttpServer();
		}
		catch (const Exception& e) // 这里捕获父类对象就可以
		{
			// 多态
			cout << e.what() << endl;
		}
		catch (...)
		{
			cout << "Unkown Exception" << endl;
		}
	}
}

用基类引用统一捕获不同的派生类对象,实现多态,规范了异常体系。防止有人乱抛异常,导致项目程序终止。

四、标准库异常体系


列举几个常见的标准异常:

  • std::exception:该异常是所有C++标准异常的父类
  • std::bad_alloc:该异常通过new抛出
  • std::out_of_range:该异常越界抛出
int main()
{
	try
	{
		vector<int> v(10, 5);
		// 这里如果系统内存不够也会抛异常
		v.reserve(1000000000);
		// 这里越界会抛异常
		v.at(10) = 100;
	}
	catch (const exception& e) // 这里捕获父类对象就可以
	{
		cout << e.what() << endl;
	}
	catch (...)
	{
		cout << "Unkown Exception" << endl;
	}
	return 0;
}

ps:operator[]不会做边界检查,如果你尝试访问一个越界的索引,operator[] 会返回对应位置的引用,但这是一个未定义的行为,可能会导致程序崩溃或其他不可预测的结果。
ps:C++标准异常库设计的不够好用,实际中很多公司都是自定义一套异常体系。

总结

C++异常的优势

  1. 相比错误码的方式,可以清晰准确的展示出错误的各种信息,这样可以帮助更好的定位程序的bug。
  2. 抛出的异常可以直接跳到catch语句捕获。而返回错误码时,在函数调用链中,深层的函数返回了错误,那么得层层返回错误,最外层才能拿到错误。
  3. 很多的第三方库都包含异常,比如boost、gtest、gmock等等常用的库,那么我们使用它们也需要使用异常。
  4. 部分函数使用异常更好处理。比如构造函数没有返回值,不方便使用错误码方式处理。比如T& operator这样的函数,如果pos越界了只能使用异常或者终止程序处理,没办法通过返回值表示错误。

C++异常的缺陷

  1. 异常会导致程序的执行流乱跳,并且非常的混乱,并且是运行时出错抛异常就会乱跳。这会导致我们跟踪调试时以及分析程序时,比较困难。
  2. C++没有垃圾回收机制,资源需要自己管理。有了异常非常容易导致内存泄漏、死锁等异常安全问题。这个需要使用RAII来处理资源的管理问题。
  3. C++标准库的异常体系定义得不好,导致大家各自定义各自的异常体系,非常的混乱。

真诚点赞,手有余香


网站公告

今日签到

点亮在社区的每一天
去签到