- 异常概念
- 异常的用法
- 自定义异常体系
- 标准库异常体系
- 异常的优缺点
一.异常的概念
c语言处理错误的方式:
- 终止程序,如assert,内存错误,除0错误都会终止程序。但是用户难以接收这种错误,比如你正在运行一个程序,发生了一个错误,程序就直接退出了。
- 返回错误码,这种方式不方便读取更加详细的错误信息,需要程序员根据错误码查找错误信息,比如系统的很多库接口函数都是通过把错误码放入errno中表示错误的
- c语言大多数错误情况都是返回错误码的
因为c语言这种方式不方便读取错误信息,所以c++中用异常来处理错误。
1.概念
异常是一种错误处理机制,在一个函数中出现错误时,该函数就可以抛出异常,让函数的直接或者间接调用者来处理这个错误。
- throw:抛出异常的关键字,如果异常没有被catch,程序会退出
- try:只有在try块内抛出的异常才能被捕获,它后面通常会跟多个catch块
- catch:捕获异常,catch的参数必须和throw抛出的错误参数类型一致。
double division(int a, int b)
{
if (b == 0)
{
throw "发生除0错误";
}
else
{
return (double)a / b;
}
}
int main()
{
try
{
cout << division(3, 0);
}
catch (const char* str)
{
cout << str << endl;
}
return 0;
}
2.异常抛出和匹配的原则
- 异常是通过抛出对象而引发的,该对象的类型决定了应该激活哪个catch的处理代码。
- 被选中的处理代码是调用链中与该对象类型匹配且离抛出异常位置最近的那一个。
- 抛出异常对象后,会生成一个异常对象的拷贝,因为抛出的异常对象可能是一个临时对象,
所以会生成一个拷贝对象,这个拷贝的临时对象会在被catch以后销毁。(这里的处理类似
于函数的传值返回) - catch(…)可以捕获任意类型的异常,问题是不知道异常错误是什么。
- 实际中抛出和捕获的匹配原则有个例外,并不都是类型完全匹配,可以抛出的派生类对象,
使用基类捕获,通常都是配合多态使用。
3.函数栈帧中的异常匹配
double division(int a, int b)
{
if (b == 0)
{
try
{
throw "发生除0错误";
}
catch(const char* str)
{
cout << str << endl;
}
}
else
{
return (double)a / b;
}
}
void func()
{
try
{
cout << division(3, 0);
}
catch(const char* str)
{
cout << str << endl;
}
}
int main()
{
try
{
func();
}
catch (const char* str)
{
cout << str << endl;
}
catch (...)
{
cout << "未知异常" << endl;
}
return 0;
}
在上述代码中,如果异常throw,首先会在当前函数栈帧中检查是否有catch
- 如果有则匹配当前栈帧中的catch,匹配完之后,依次执行代码逻辑,只是不会再进入上层调用处的catch。
- 如果没有则退出当前栈帧,进入上一层栈帧,寻找是否有catch
- 直到退出到main函数,还是没有catch,那么程序就会终止。所以实际中我们最后都要加一个catch(…)捕获任意类型的异常,否则当有异常没捕获,程序就会直接终止。
一般我们都是在最外层处理异常,上述步骤只是为了展示异常栈展开
二.异常的用法
在项目工程中,异常的使用不是象上面那样(抛出内置类型),因为包含的错误信息太少了,一般都是抛出一个自定义类型,以便有更多的错误信息。
class Exception
{
public:
Exception(int errid, const string& errmsg)
:_errid(errid)
, _errmsg(errmsg)
{}
int GetErrid() const
{
return _errid;
}
const char* GetErrmsg() const
{
return _errmsg.c_str();
}
private:
//错误码
int _errid;
//错误信息
string _errmsg;
};
double division(int a, int b)
{
if (b == 0)
{
throw Exception(0, "发生除0错误");
}
else
{
return (double)a / b;
}
}
int main()
{
try
{
cout << division(3, 0);
}
catch (const Exception& e)
{
cout << e.GetErrid() << " : ";
cout << e.GetErrmsg() << endl;
}
catch (...) //为了增强程序的健壮性,防止程序退出
{
cout << "未知异常" << endl;
}
return 0;
}
1.异常的重新抛出
通常我们都是在main函数来处理异常的,throw异常时,会导致程序的执行流直接跳到main函数中,此时就会存在一些问题,如果我们在销毁的栈帧中,有一个new函数,此时程序在匹配catch时,会跳过剩下的代码,直接找catch就会出现内存泄漏的问题。
class Exception
{
public:
Exception(int errid, const string& errmsg)
:_errid(errid)
, _errmsg(errmsg)
{}
int GetErrid() const
{
return _errid;
}
const char* GetErrmsg() const
{
return _errmsg.c_str();
}
private:
//错误码
int _errid;
//错误信息
string _errmsg;
};
double division(int a, int b)
{
if (b == 0)
{
throw Exception(0, "发生除0错误");
}
else
{
return (double)a / b;
}
}
void func()
{
int* arr = new int[10];
cout << division(3, 0);
delete[] arr;
arr = nullptr;
}
int main()
{
try
{
func();
}
catch (const Exception& e)
{
cout << e.GetErrid() << " : ";
cout << e.GetErrmsg() << endl;
}
catch (...)
{
cout << "未知异常" << endl;
}
return 0;
}
上述代码在运行时,就会出现内存泄漏,45 45行的代码就会被跳过,要防止这种情况的发生,就需要用到异常的重新抛出
class Exception
{
public:
Exception(int errid, const string& errmsg)
:_errid(errid)
, _errmsg(errmsg)
{}
int GetErrid() const
{
return _errid;
}
const char* GetErrmsg() const
{
return _errmsg.c_str();
}
private:
//错误码
int _errid;
//错误信息
string _errmsg;
};
double division(int a, int b)
{
if (b == 0)
{
throw Exception(0, "发生除0错误");
}
else
{
return (double)a / b;
}
}
void func()
{
int* arr = new int[10];
try
{
cout << division(3, 0);
}
catch(...) //...代表任意类型,这里的捕获异常但是并不处理异常,重新抛出,
{ //这里捕获异常就是为了防止发生内存泄漏
delete[] arr;
arr = nullptr;
throw; //语法规定,这样写就是异常的重写抛出
}
}
int main()
{
try
{
func();
}
catch (const Exception& e)
{
cout << e.GetErrid() << " : ";
cout << e.GetErrmsg() << endl;
}
catch (...)
{
cout << "未知异常" << endl;
}
return 0;
}
2.异常规范
c语言:
- 异常规格说明的目的是为了让函数使用者知道该函数可能抛出的异常有哪些。 可以在函数的
后面接throw(类型),列出这个函数可能抛掷的所有异常类型。 - 函数的后面接throw(),表示函数不抛异常。
- 若无异常接口声明,则此函数可以抛掷任何类型的异常。
c++:
- 如果该函数不抛出异常,则声明为noexcept
- 如果该函数抛出异常,则啥都不加
// 这里表示这个函数会抛出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;
3.异常安全
- 构造函数完成对象的构造和初始化,最好不要在构造函数中抛出异常,否则可能导致对象不完整或没有完全初始化
- 析构函数主要完成资源的清理,最好不要在析构函数内抛出异常,否则可能导致资源泄漏(内存泄漏、句柄未关闭等)
- C++中异常经常会导致资源泄漏的问题,比如在new和delete中抛出了异常,导致内存泄漏,在lock和unlock之间抛出了异常导致死锁,C++经常使用RAII来解决以上问题。(智能指针)
三.自定义异常体系
实际使用中很多公司都会自定义自己的异常体系进行规范的异常管理,因为一个项目中如果大家随意抛异常,那么外层的调用者基本就没办法玩了,所以实际中都会定义一套继承的规范体系。 这样大家抛出的都是继承的派生类对象,捕获一个基类就可以了(基类与派生类的赋值兼容规则转换),通常这些还会实现为多态,在异常处理时,只要调用虚函数即可。
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#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;
};
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)
{
this_thread::sleep_for(chrono::seconds(1));
try {
HttpServer();
}
catch (const Exception& e) // 这里捕获父类对象就可以
{
// 多态
cout << e.what() << endl;
}
catch (...)
{
cout << "Unkown Exception" << endl;
}
}
return 0;
}
四.标准库异常体系
C++ 提供了一系列标准的异常,定义在STL中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的,在头文件exception
中,但是这个异常体系并不好用。
五.异常的优缺点
1.异常的优点
- 可以更加清晰的展示错误信息,有利于定位bug
- 返回错误码的方式,需要函数层层返回,而异常是直接返回到catch处
- 很多的第三方库都包含异常,比如boost、gtest、gmock等等常用的库,那么我们使用它们也需要使用异常
- 部分函数使用异常更好处理,比如构造函数没有返回值,不方便使用错误码方式处理。比如T& operator这样的函数,如果pos越界了只能使用异常或者终止程序处理,没办法通过返回值表示错误。
2.异常的缺点
- c++没有垃圾回收机制,所以异常很容器导致内存泄漏的问题发生,new/malloc/lock/fopen时,发生内存泄漏/死锁
- 异常会导致程序的执行流乱跳,不便于调试
- c++标准库的异常体系不好,因此大家各自定义不同的异常体系,很混乱
- 异常尽量规范使用,否则后果不堪设想,随意抛异常,外层捕获的用户苦不堪言。所以异常规范有两点:一、抛出异常类型都继承自一个基类。二、函数是否抛异常、抛什么异常,都使用 func() noexcept;的方式规范化。