• C++异常


    C++异常概念

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

    1. 终止程序,如assert,缺陷:用户难以接受。如发生内存错误,除0错误时就会终止程序。
    2. 返回错误码,缺陷:需要程序员自己去查找对应的错误。如系统的很多库的接口函数都是通过把错误码放到errno中,表示错误。
      实际中C语言基本都是使用返回错误码的方式处理错误,部分情况下使用终止程序处理非常严重的错误。

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

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

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

    #include
    using namespace std;
    
    int Division(int x, int y)
    {
    	if (y == 0)//如果等于0就抛异常
    		throw "除0错误";
    	else
    		return x / y;
    	cout << 22222 << endl;
    }
    void func()
    {
    	int a, b;
    	cin >> a >> b;
    	cout << Division(a, b) << endl;
    }
    int main()
    {
    	try
    	{
    		func();
    	}
    	catch(const char* str)//捕获异常
    	{
    		cout << str << endl;
    	}
    	cout << 111111 << endl;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    在这里插入图片描述
    这里会直接抛异常,不会终止,但是不会处理异常函数的后续内容。

    异常的使用

    异常的抛出和匹配原则

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

    捕获异常不允许相同类型:
    在这里插入图片描述
    如果类型不匹配,就会终止程序:
    在这里插入图片描述
    在函数调用链中异常栈展开匹配原则

    1. 首先检查throw本身是否在try块内部,如果是再查找匹配的catch语句。如果有匹配的,则
      调到catch的地方进行处理。
    2. 没有匹配的catch则退出当前函数栈,继续在调用函数的栈中进行查找匹配的catch。
    3. 如果到达main函数的栈,依旧没有匹配的,则终止程序。上述这个沿着调用链查找匹配的
      catch子句的过程称为栈展开。所以实际中我们最后都要加一个catch(…)捕获任意类型的异
      常,否则当有异常没捕获,程序就会直接终止。
    4. 找到匹配的catch子句并处理以后,会继续沿着catch子句后面继续执行。
    #include
    using namespace std;
    
    int Division(int x, int y)
    {
    	if (y == 0)//如果等于0就抛异常
    		throw "除0错误";
    	else
    		return x / y;
    	cout << 22222 << endl;
    }
    void func()
    {
    	try
    	{
    		int a, b;
    		cin >> a >> b;
    		cout << Division(a, b) << endl;
    	}
    	catch (const char* str)//这里异常返回的是最近的一个
    	{
    		cout << str << endl;
    	}
    	cout << 33333 << endl;
    }
    int main()
    {
    	try
    	{
    		func();
    	}
    	catch(const char* str)
    	{
    		cout << str << endl;
    	}
    	cout << 111111 << endl;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    在这里插入图片描述
    这种的好处就是,如果在一个函数中开辟了内存,中途抛异常之后还能继续向后走,后面又释放内存的语句就不会被遗漏。

    在这里插入图片描述
    还有重新抛出的操作:

    #include
    using namespace std;
    
    int Division(int x, int y)
    {
    	if (y == 0)//如果等于0就抛异常
    		throw "除0错误";
    	else
    		return x / y;
    	cout << 22222 << endl;
    }
    void func()
    {
    	int* p = new int(0);
    	try
    	{
    		int a, b;
    		cin >> a >> b;
    		cout << Division(a, b) << endl;
    	}
    	catch (const char* str)
    	{
    		cout << str << endl;
    		delete p;//为了释放资源
    		throw str;//重新抛出
    	}
    	cout << 33333 << endl;
    }
    int main()
    {
    	try
    	{
    		func();
    	}
    	catch(const char* str)
    	{
    		cout << str << endl;
    	}
    	cout << 111111 << endl;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    在这里插入图片描述
    这里还可以捕获任意类型的异常:

    #include
    using namespace std;
    
    int Division(int x, int y)
    {
    	if (y == 0)//如果等于0就抛异常
    		throw "除0错误";
    	else
    		return x / y;
    	cout << 22222 << endl;
    }
    void func()
    {
    	int* p = new int(0);
    	try
    	{
    		int a, b;
    		cin >> a >> b;
    		cout << Division(a, b) << endl;
    	}
    	catch (...)//捕获任意类型异常
    	{
    		delete p;//为了释放资源
    		throw;//捕获到什么就抛出什么
    	}
    	cout << 33333 << endl;
    }
    int main()
    {
    	try
    	{
    		func();
    	}
    	catch(const char* str)
    	{
    		cout << str << endl;
    	}
    	cout << 111111 << endl;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    在这里插入图片描述
    我们要注意一点,捕获的内容是拷贝过来的。
    此外,捕获任意异常的场景一般多是防止发生未知异常,因为有些时候程序员会有一些失误,抛异常的类型不匹配,但是程序又不能崩溃。

    那么,如果一个项目中,各种小组的问题都抛异常给了后面网络层的,那么接收是个非常头疼的问题,这时候就可以用一个基类来接收这些异常类了,可以形成多态。

    #include
    #include
    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;
    };
    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(1000);
    		try {
    			HttpServer();
    		}
    		catch (const Exception& e) // 这里捕获父类对象就可以
    		{
    			// 多态
    			cout << e.what() << endl;
    		}
    		catch (...)
    		{
    			cout << "Unkown Exception" << endl;
    		}
    	}
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124

    在这里插入图片描述

    异常安全与规范

    安全

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

    规范

    异常规格说明的目的是为了让函数使用者知道该函数可能抛出的异常有哪些。 可以在函数的
    后面接throw(类型),列出这个函数可能抛掷的所有异常类型。
    函数的后面接throw(),表示函数不抛异常。
    若无异常接口声明,则此函数可以抛掷任何类型的异常。

    // 这里表示这个函数会抛出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;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    C++标准库的异常体系

    C++ 提供了一系列标准的异常,定义在 中,我们可以在程序中使用这些标准的异常。它们是以父
    子类层次结构组织起来的,如下所示:
    在这里插入图片描述
    在这里插入图片描述
    说明:实际中我们可以可以去继承exception类实现自己的异常类。但是实际中很多公司像上面一
    样自己定义一套异常继承体系。因为C++标准库设计的不够好用。

    #include
    #include
    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    在这里插入图片描述

    异常的优缺点

    C++异常的优点:

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

    C++异常的缺点:

    1. 异常会导致程序的执行流乱跳,并且非常的混乱,并且是运行时出错抛异常就会乱跳。这会
      导致我们跟踪调试时以及分析程序时,比较困难。
    2. 异常会有一些性能的开销。当然在现代硬件速度很快的情况下,这个影响基本忽略不计。
    3. C++没有垃圾回收机制,资源需要自己管理。有了异常非常容易导致内存泄漏、死锁等异常
      安全问题。这个需要使用RAII来处理资源的管理问题。学习成本较高。
    4. C++标准库的异常体系定义得不好,导致大家各自定义各自的异常体系,非常的混乱。
    5. 异常尽量规范使用,否则后果不堪设想,随意抛异常,外层捕获的用户苦不堪言。所以异常
      规范有两点:一、抛出异常类型都继承自一个基类。二、函数是否抛异常、抛什么异常,都
      使用 func() throw();的方式规范化。

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

  • 相关阅读:
    鸿蒙媒体开发【相机数据采集保存】拍照和图片
    【JS 的数据类型】
    <计算机网络自顶向下> TCP拥塞
    ROS2-IRON Ubuntu-22.0 源码下载失败解决方法 vcs import --input
    老司机带带你,教你学会Java中又骚又暴力的“反射”技术
    python 连接Oracle db
    gerrit部署使用
    Linux:kubernetes(k8s)探针LivenessProbe的使用(9)
    Pymol做B因子图
    【嵌入式软件开发岗位 ---- 面试总结01】
  • 原文地址:https://blog.csdn.net/qq_63580639/article/details/131140403