1.异常相关概念

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

1.1 throw表达式

​ 程序的异常检测部分使用throw表达式引发一个异常。throw表达式包含关键字throw和紧随其后的一个表达式,其中表达式的类型就是抛出的异常类型。

1.2 try语句块

​ catch子句包括三部分:关键字catch、括号内一个(可能未命名的)对象的声明(称作异常声明,exception declaration)以及一个块。当选中某个catch子句处理异常之后,执行与之对应的块。catch一旦完成,程序跳转到try语句块最后一个catch子句之后的那条语句继续执行。

1.3标准异常

C++标准库定义了一组类,用于报告标准库函数遇到的问题。这些异常类也可以在用户编写的程序中使用,它们分别在4个文件头中:

异常类型只定义了一个名为what的成员函数,该函数没有任何参数,返回值是一个指向C风格的字符串的const char*。该字符串的目的是提供关于异常的一些文本信息。

2.异常的使用

2.1 异常的抛出和捕获

异常的抛出和匹配原则:

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

#include <iostream>
#include <stdexcept>
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;
	std::cin >> len >> time;
	std::cout << Division(len, time) << std::endl;
}

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

	return 0;
}

键盘输入10和0,分别表示a和b,所得结果:

image-20250922193659744

2.2异常的重新抛出

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

void Func()
{
	int* array = new int[10];
	try
	{
		int len, time;
		std::cin >> len >> time;
		std::cout << Division(len, time) << std::endl;
	}
	catch (...)
	{
		std::cout << "delete []" << array << std::endl;
		delete[] array;
		throw;
	}

	std::cout << "delete[]" << array << std::endl;
	delete[] array;
}

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

image-20250922200545455

2.3异常安全

2.4异常规范

void func() throw(A,B,C,D);//func函数会抛出A/B/C/D中的某种类型的异常
void* operator new(std::size_t size) throw(std::bad_alloc);//这个函数只会抛出bad_alloc的异常
void* operator delete(std::size_t size ,void* ptr)throw();//表示这个函数不会抛出异常

shared_ptr()noexcept;//C++11新增noexcept,表示不会抛出异常

3.自定义异常体系

下面展示一段服务器开发过程中常用的异常继承体系:

#include <iostream>
#include <stdexcept>
#include <string>
#include <thread>

class Exception {
public:
	Exception(int errid,const const std::string& msg)
		:_errid(errid)
		,_errmsg(msg)
	{ }

	const std::string& GetMsg()const
	{
		return _errmsg;
	}

	int GetErrid()const
	{
		return _errid;
	}

	virtual std::string what()const
	{
		return _errmsg;
	}

protected:
	int _errid;//error code
	std::string _errmsg;//error description
};

class sqlException : public Exception
{
public:
	sqlException(int errid, const std::string& msg, const std::string& sql)
		:Exception(errid, msg)
		,_sql(sql)
	{ }

	virtual std::string what()const
	{
		std::string str = "sqlException: ";
		str += _errmsg;
		str += "->";
		str += _sql;

		return str;
	}
private:
	const std::string _sql;
};

class cacheException :public Exception
{
public:
	cacheException(int errid,const std::string& errmsg)
		:Exception(errid,errmsg)
	{ }

	virtual std::string what()const
	{
		std::string str = "cacheException:";
		str += _errmsg;
		return str;
	}
};

class httpServerException :public Exception
{
public:
	httpServerException(int errid,const std::string& errmsg,const std::string& type)
		:Exception(errid,errmsg)
		,_type(type)
	{ }

	virtual std::string what()const
	{
		std::string str = "httpServerException:";
		str += _type;
		str += ":";
		str += _errmsg;
		return str;
	}

private:
	const std::string _type;
};

void SQLMgr()
{
	srand(time(0));
	if (rand() % 7 == 0)
	{
		throw sqlException(100,"权限不足", "select* from name = '张飞'");
	}
}

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 (true)
	{
		std::this_thread::sleep_for(std::chrono::seconds(1));
		try
		{
			HttpServer();
		}
		catch (const Exception& e)
		{
			//多态
			std::cout << e.what() << std::endl;
		}
		catch (...)
		{
			std::cout << "unkown exception" << std::endl;
		}
	}
	return 0;
}

4.C++标准库的异常体系

C++提供了一系列标准的异常,定义在exception中,我们可以在程序中使用这些标准异常。它们以父子类层次结构组织起来的,具体如下:

异常描述
std::exception该异常说所有标准C++异常的父类
std::bad_alloc该异常可以通过new抛出
std::bad_cast该异常可以通过dynamic_cast抛出
std::bad_exception这在处理C++程序中无法预期的异常时非常有用
std::bad_typeid该异常可以通过typeid抛出
std::logic_error理论上可以通过读取代码来检测到的异常
std::domain_error当使用一个无效的数学域时,会抛出该异常
std::invalid_argument当使用了无效的参数时,会抛出该异常
std::length_error当创建了太长的std::string时,会抛出该异常
std::out_of_range该异常可以通过方法抛出,例如std::vector和std::bitset<>::operator
std::runtime_error理论上不可以通过读取代码来检测到的异常
std::overflow_error当发生数学上溢时,会抛出该异常
std::range_error当尝试存储超出范围的值时,会抛出该异常
std::underflow_error当发生数学下溢时,会抛出该异常

说明:实际中,我们可以去继承exception类实现自己的异常类。但是实际开发过程中,会自定义一套异常继承体系,因为C++标准库设计的异常不够好用。

5.异常的优缺点

C++异常的优点

C++异常得缺点

本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:[email protected]