
🚀write in front🚀
📜所属专栏: C++学习
🛰️博客主页:睿睿的博客主页
🛰️代码仓库:🎉VS2022_C语言仓库
🎡您的点赞、关注、收藏、评论,是对我最大的激励和支持!!!
关注我,关注我,关注我,你们将会看到更多的优质内容!!

异常是一种处理错误的方式,当一个函数发现自己无法处理的错误时就可以抛出异常,让函数的直接或间接的调用者处理这个错误。
在异常里面,我们分别用throw(抛出异常),catch(捕获异常),try(激活特定异常)这三个关键字来捕获异常。用法如下:
try//表示异常要开始捕获了
{
// 保护的标识代码
throw .....//抛出异常
}
catch( ExceptionName e1 )//根据异常的类型接收异常
{
// catch 块
}
catch( ExceptionName e2 )
{
// catch 块
}
catch( ExceptionName eN )
{
// catch 块
}
记住!!抛出异常一定要在try里面(现有函数栈帧里的try里面抛出异常或异常在函数抛出,但是函数调用在try里面,这两个都可以),这是前提!不然就会报错!!
举个🌰🌰
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;
cout << "yyyyyyyyy" << endl;
}
int main()
{
Func();
try
{
cout << "你干嘛哎哟" << endl;
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch (...)
{
cout << "unknown exception" << endl;
}
return 0;
}
这里的func就没有在try里面,程序就会强制报错:

catch(...)可以捕获任意类型的异常,问题是不知道异常错误是什么。catch语句,try里面的抛出异常语句的后面几句就不会执行了。catch(...)捕获任意类型的异常,否则当有异常没捕获,程序就会直接终止。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;
cin >> len >> time;
cout << Division(len, time) << endl;
}
int main()
{
try
{
Func();
}
catch (int errmsg)
{
cout << errmsg << endl;
}
return 0;
}


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;
cin >> len >> time;
cout << Division(len, time) << endl;
cout << "yyyyyyyyy" << endl;//如果抛出异常,直接跳到catch,执行不到这一句了
}
int main()
{
try {
Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch(...)//处理其他情况
{
cout<<"unkown exception"<<endl;
}
cout<<" hh"<<endl;//catch后面的代码继续执行。
return 0;
}


有可能单个的catch不能完全处理一个异常,在进行一些校正处理以后,希望再交给更外层的调用链函数来处理,catch则可以通过重新抛出将异常传递给更上层的函数进行处理。
我们来看看下面的🌰:
double Division(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
{
throw "Division by zero condition!";
}
return (double)a / (double)b;
}
void Func()
{
// 这里可以看到如果发生除0错误抛出异常,另外下面的array没有得到释放。
int* array = new int[10];
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;//在这里直接跳catch去了,下面的语句就不会执行了
cout << "delete []" << array << endl;
delete[] array;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
return 0;
}
在这里我们就会发现,由于异常的跳跃,空间没有得到释放。那么怎么解决这个问题呢?
double Division(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
{
throw "Division by zero condition!";
}
return (double)a / (double)b;
}
void Func()
{
int* array = new int[10];
try
{
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
// func()
}
catch (...) // 异常的重新抛出,为了内存释放
{
cout << "delete []" << array << endl;
delete[] array;
throw; // 捕获什么,抛什么
}
//...
cout << "delete []" << array << endl;
delete[] array;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
return 0;
}

这里我们就要用到异常的重新抛出!!这里捕获异常后并不处理异常,而是为了内存释放,异常还是交给外面处理!!
// 这里表示这个函数会抛出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;
我们来看看new的底层就知道了:

这里就是说抛出类型一定是bad_alloc(_RAISE是宏定义,就是throw)
在服务器开发里面,异常是怎么工作的呢?
首先异常就封装了一个类如下:
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 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++里面自己就有一系列标准的异常,定义在 中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的。

说明:实际中我们自己可以去继承exception类实现自己的异常类。但是实际中很多公司像上面一样自己定义一套异常继承体系。因为C++标准库设计的不够好用。
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.下面这段伪代码我们可以看到ConnnectSql中出错了,先返回给ServerStart,
ServerStart再返回给main函数,main函数再针对问题处理具体的错误。
// 2.如果是异常体系,不管是ConnnectSql还是ServerStart及调用函数出错,都不用检查,因
为抛出的异常异常会直接跳到main函数中catch捕获的地方,main函数直接处理错误。
int ConnnectSql()
{
// 用户名密码错误
if (...)
return 1;
// 权限不足
if (...)
return 2;
}
int ServerStart() {
if (int ret = ConnnectSql() < 0)
return ret;
int fd = socket()
if(fd < 0)
return errno;
}
int main()
{
if(ServerStart()<0)
...
return 0;
}
总结:异常总体而言,利大于弊,所以工程中我们还是鼓励使用异常的。另外OO的语言基本都是用异常处理错误,这也可以看出这是大势所趋。
更新不易,辛苦各位小伙伴们动动小手,👍三连走一走💕💕 ~ ~ ~ 你们真的对我很重要!最后,本文仍有许多不足之处,欢迎各位认真读完文章的小伙伴们随时私信交流、批评指正!
专栏订阅:
每日一题
C语言学习
算法
智力题
初阶数据结构
Linux学习
C++学习
更新不易,辛苦各位小伙伴们动动小手,👍三连走一走💕💕 ~ ~ ~ 你们真的对我很重要!最后,本文仍有许多不足之处,欢迎各位认真读完文章的小伙伴们随时私信交流、批评指正!
