C++第四十七弹---深入理解异常机制:try, catch, throw全面解析

发布于:2024-09-18 ⋅ 阅读:(132) ⋅ 点赞:(0)

个人主页: 熬夜学编程的小林

💗系列专栏: 【C语言详解】 【数据结构详解】【C++详解】

目录

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

2.C++异常概念

3. 异常的使用

3.1 异常的抛出和捕获

3.2 异常的重新抛出

3.3 异常安全

3.4 异常规范

4.自定义异常体系

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


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

传统的错误处理机制:

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

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

2.C++异常概念

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

  • throw: 当问题出现时,程序会抛出一个异常。这是通过使用 throw 关键字来完成的。
  • catch: 在您想要处理问题的地方,通过异常处理程序捕获异常 catch 关键字用于捕获异常,可以有多个catch进行捕获。
  • try: try 块中的代码标识将被激活的特定异常,它后面通常跟着一个或多个 catch 块。

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

try
{
 // 保护的标识代码
}catch( ExceptionName e1 )
{
 // catch 块
}catch( ExceptionName e2 )
{
 // catch 块
}catch( ExceptionName eN )
{
 // catch 块
}

3. 异常的使用

3.1 异常的抛出和捕获


异常的抛出和匹配原则

  • 1. 异常是通过抛出对象而引发的,该对象的类型决定了应该激活哪个catch的处理代码
  • 2. 被选中的处理代码调用链中与该对象类型匹配且离抛出异常位置最近的那一个
  • 3. 抛出异常对象后,会生成一个异常对象的拷贝,因为抛出的异常对象可能是一个临时对象,所以会生成一个拷贝对象,这个拷贝的临时对象会在被catch以后销毁。(这里的处理类似于函数的传值返回)
  • 4. catch(...)可以捕获任意类型的异常,问题是不知道异常错误是什么。
  • 5. 实际中抛出和捕获的匹配原则有个例外,并不都是类型完全匹配,可以抛出的派生类对象,使用基类捕获,这个在实际中非常实用,我们后面会详细讲解这个。

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

  • 1. 首先检查throw本身是否在try块内部,如果是再查找匹配的catch语句。如果有匹配的,则调到catch的地方进行处理。
  • 2. 没有匹配的catch则退出当前函数栈,继续在调用函数的栈中进行查找匹配的catch。
  • 3. 如果到达main函数的栈,依旧没有匹配的,则终止程序。上述这个沿着调用链查找匹配的catch子句的过程称为栈展开。所以实际中我们最后都要加一个catch(...)捕获任意类型的异常,否则当有异常没捕获,程序就会直接终止。
  • 4. 找到匹配的catch子句并处理以后,会继续沿着catch子句后面继续执行。

代码演示 

#include<iostream>
using namespace std;
double Division(int a, int b)
{
	// 当b == 0时抛出异常
	if (b == 0)
		throw "Division by zero condition!";
		//throw 1;
	else
		return ((double)a / (double)b);
}
void Func()
{
	int len, time;
	cin >> len >> time;
	cout << Division(len, time) << endl;
}
int main()
{
	try 
	{
		Func();
	}
	// 抛出什么类型用什么接受
	catch (const char* errmsg)
	{
		cout << errmsg << endl;
	}
	catch (const int i)
	{
		cout << i << endl;
	}
	// 可以接受任意类型
	catch (...) 
	{
		cout << "unkown exception" << endl;
	}
	return 0;
}

运行结果 

 

3.2 异常的重新抛出

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

代码演示

#include<iostream>
#include<string>
using namespace std;
// 重新抛出
double Division(int a, int b)
{
	// 当b == 0时抛出异常
	if (b == 0)
	{
		throw "Division by zero condition!";
		//string str("Division by zero condition!");
		//throw str;

		//throw 1;
	}
	else
	{
		return ((double)a / (double)b);
	}
}
void Func()
{
	try
	{
		int len, time;
		cin >> len >> time;
		cout << Division(len, time) << endl;
	}
	// 有两个类型相同异常,就近调用
	catch (const char* err)
	{
		cout << err << endl;
	}
	// 异常捕获之后后面能够一直执行
	cout << "xxxxxxxxx" << endl;
}

int main()
{
	try 
	{
		Func();
	}
	// 需要类型匹配
	catch (const char* errmsg)
	{
		cout << errmsg << endl;
	}
	catch (const string& s)
	{
		cout << s << endl;
	}
	// 可以捕获任意类型异常
	catch (...) 
	{
		cout << "unkown exception" << endl;
	}
	return 0;
}

运行结果 

3.3 异常安全

  • 构造函数完成对象的构造和初始化最好不要在构造函数中抛出异常,否则可能导致对象不完整或没有完全初始化。
  • 析构函数主要完成资源的清理最好不要在析构函数内抛出异常,否则可能导致资源泄漏(内存泄漏、句柄未关闭等)。
  • C++中异常经常会导致资源泄漏的问题,比如在new和delete中抛出了异常,导致内存泄漏,在lock和unlock之间抛出了异常导致死锁,C++经常使用RAII来解决以上问题,关于RAII我们智能指针这节进行讲解。

3.4 异常规范

  • 1. 异常规格说明的目的是为了让函数使用者知道该函数可能抛出的异常有哪些。 可以在函数的后面接throw(类型),列出这个函数可能抛掷的所有异常类型。
  • 2. 函数的后面接throw(),表示函数不抛异常。
  • 3. 若无异常接口声明,则此函数可以抛掷任何类型的异常。 
// 这里表示这个函数会抛出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;

4.自定义异常体系


实际使用中很多公司都会自定义自己的异常体系进行规范的异常管理,因为一个项目中如果大家随意抛异常,那么外层的调用者基本就没办法玩了,所以实际中都会定义一套继承的规范体系。这样大家抛出的都是继承的派生类对象,捕获一个基类就可以了。

代码演示 

#include<iostream>
#include<string>
#include<thread>
using namespace std;
// 服务器开发的异常体系
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((unsigned int)time(0));
	if (rand() % 7 == 0)
	{
		throw SqlException("权限不足", 100, "select * from name = '张三'");
	}
	else
	{
		cout << "执行Sql成功" << endl;
	}
}
void CacheMgr()
{
	srand((unsigned int)time(0));
	if (rand() % 5 == 0)
	{
		throw CacheException("权限不足", 100);
	}
	else if (rand() % 6 == 0)
	{
		throw CacheException("数据不存在", 101);
	}
	else
	{
		cout << "Cache获取成功" << endl;
	}

	SQLMgr();
}
void HttpServer()
{
	// ...
	srand((unsigned int)time(0));

	if (rand() % 3 == 0)
	{
		throw HttpServerException("请求资源不存在", 100, "get");
	}
	else if (rand() % 4 == 0)
	{
		throw HttpServerException("权限不足", 101, "post");
	}
	else
	{
		cout << "http调用成功" << endl;
	}

	CacheMgr();
}
int main()
{
	while (1)
	{
		// 休眠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;
}

运行结果 

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


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

说明:实际中我们可以可以去继承exception类实现自己的异常类。但是实际中很多公司像上面一
样自己定义一套异常继承体系。因为C++标准库设计的不够好用。

标准库代码演示

#include<iostream>
#include<vector>
using namespace std;
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;
}

运行结果 


网站公告

今日签到

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