目录
概念
使用
异常的抛出和捕获
栈展开
catch匹配
继承体系例子
异常重新抛出
异常安全问题
例:
异常规范
小知识
概念
异常处理机制允许程序中独⽴开发的部分能够在运⾏时就出现的问题进⾏通信并做出相应的处理, 异常使得我们能够将问题的检测与解决问题的过程分开,程序的⼀部分负责检测问题的出现,然后 解决问题的任务传递给程序的另⼀部分,检测环节⽆须知道问题的处理模块的所有细节。
C语⾔主要通过错误码的形式处理错误,错误码本质就是对错误信息进⾏分类编号,拿到错误码以 后还要去查询错误信息,⽐较⿇烦。异常时抛出⼀个对象,这个对象可以函数更全⾯的各种信息。
使用
异常的抛出和捕获
1.程序出现问题时,通过抛出(throw)一个对象来引发一个异常,该对象的类型以及当前的调用链决定应该由哪个catch来处理该异常。
2.对于抛出对象和catch的匹配:找调用链中距离抛出位置最近并且参数匹配的catch,由catch中的代码来告知异常是什么错误。
3.throw执行后,其之后的语句将不会执行。程序执行从throw位置跳到与之匹配的catch模块。这意味着:(1)沿着调用链的函数可能提早退出。 (2)一旦程序开始执行异常处理程序,直到匹配位置,沿着调用链创建的对象都会销毁。
4.抛出异常后,会生成一个异常对象的拷贝,在catch模块后销毁。(类似函数传值返回)
5.异常对象与catch匹配的条件是该异常抛出在try内部,try与catch是对应的,一个try可以与大于等于1个catch搭配。
例:下面的可以直接throw,不用写throw e
int fun4(int a, int b)
{
try
{
if (a - b)
{
string e = "fun4()";
throw e;
}
}
catch (double s)
{
cout <<"fun4::" << s << endl;
}
}int fun3(int a, int b)
{
try
{
if (a - b > 100)
{
string e = "fun3()";
throw e;
}
fun4(a, b);
}
catch (string& s)
{
cout << "fun3::" << s << endl;
}
}int fun2(int a, int b)
{
try
{
if (a - b < 0)
{
string e = "fun2()";
throw e;
}
fun3(a, b);
}
catch (const string& s)
{
cout <<"fun2::" << s << endl;
}
}int main()
{
int x = 0, y = 0;
while (1)
{
try
{
cin >> x >> y;
fun2(x, y);
}
catch (const int& x)
{
cout << "main()" << endl;
}
}
return 0;
}
栈展开
如果当前函数中没有try/catch语句,或者有但类型不匹配,则在外层调用函数链中查找,如果找到匹配catch,执行catch中代码,到了main函数中依旧未找到,程序会调用标准库中的terminate函数终止程序。
catch匹配
⼀般情况下抛出对象和catch是类型完全匹配的,如果有多个类型匹配的,就选择离他位置更近的那个。
但是也有⼀些例外,允许从⾮常量向常量的类型转换,也就是权限缩⼩;允许数组转换成指向数组元素类型的指针,函数被转换成指向函数的指针;允许从派⽣类向基类类型的转换,这个点⾮常实⽤,实际中继承体系基本都是⽤这个⽅式设计的。
如果到main函数,异常仍旧没有被匹配就会终⽌程序,不是发⽣严重错误的情况下,我们是不期望 程序终⽌的,所以⼀般main函数中最后都会使⽤catch(...),它可以捕获任意类型的异常,但是是 不知道异常错误是什么。
继承体系例子
#include <thread>
#include <iostream>
using namespace std;
class Exception
{
public:
Exception(const string& errmsg, int id)
:_errmsg(errmsg)
, _id(id)
{
}
virtual string what() const
{
return _errmsg;
}
int getid() const
{
return _id;
}
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 HttpException : public Exception
{
public:
HttpException(const string& errmsg, int id, const string& type)
:Exception(errmsg, id)
, _type(type)
{
}
virtual string what() const
{
string str = "HttpException:";
str += _type;
str += ":";
str += _errmsg;
return str;
}
private:
const string _type;
};
void SQLMgr()
{
if (rand() % 7 == 0)
{
throw SqlException("权限不⾜", 100, "select * from name = '张三'");
}
else
{
cout << "SQLMgr 调⽤成功" << endl;
}
}
void CacheMgr()
{
if (rand() % 5 == 0)
{
throw CacheException("权限不⾜", 100);
}
else if (rand() % 6 == 0)
{
throw CacheException("数据不存在", 101);
}
else
{
cout << "CacheMgr 调⽤成功" << endl;
}
SQLMgr();
}
void HttpServer()
{
if (rand() % 3 == 0)
{
throw HttpException("请求资源不存在", 100, "get");
}
else if (rand() % 4 == 0)
{
throw HttpException("权限不⾜", 101, "post");
}
else
{
cout << "HttpServer调⽤成功" << endl;
}
CacheMgr();
}
int main()
{
srand(time(0));
while (1)
{
this_thread::sleep_for(chrono::seconds(1));//thread头文件中的函数,用来sleep程序。
try
{
HttpServer();
}
catch (const Exception& e) // 这⾥捕获基类,基类对象和派⽣类对象都可以被捕获
{
cout << e.what() << endl;
}
catch (...)
{
cout << "Unkown Exception" << endl;
}
}
return 0;
}上面我们可以看到,通过派生类向基类的转换,可以收集到各个地方的异常,针对性处理。
异常重新抛出
有时catch到⼀个异常对象后,需要对错误进⾏分类,其中的某种异常错误需要进⾏特殊的处理,其他 错误则重新抛出异常给外层调⽤链处理。捕获异常后需要重新抛出,直接 throw; 就可以把捕获的对 象直接抛出。
例子:
class Exception
{
public:
Exception(const string& errmsg, int id)
:_errmsg(errmsg)
, _id(id)
{
}
virtual string what() const
{
return _errmsg;
}
int getid() const
{
return _id;
}
protected:
string _errmsg;
int _id;
};class HttpException : public Exception
{
public:
HttpException(const string& errmsg, int id, const string& type)
:Exception(errmsg, id)
, _type(type)
{
}
virtual string what() const
{
string str = "HttpException:";
str += _type;
str += ":";
str += _errmsg;
return str;
}
private:
const string _type;
};void Message(const string& s)
{
if (rand() % 2 == 0)
{
throw HttpException("网络繁忙,重新发送中。。。",44,"put");
}
else if (rand() % 3 == 0)
{
throw HttpException("对方暂时不是你的好友",555,"put");
}
else
{
cout << "发送成功\a"<<endl;
}
}void send(const string& s)
{
//发送失败的话,再重试3次
for (int i = 0; i < 4; i++)
{
try
{
Message(s);
break;//发送成功直接退出
}
catch (const Exception& e)
{
if (e.getid() == 44)
{
if (i == 3)
throw;
cout << "number " << i + 1 << endl;
}
else
throw;
}
}
}int main()
{
srand(time(nullptr));
string str;
while (cin >> str)
{
try
{
send(str);
}
catch (const Exception& e)
{
cout << e.what() << endl;
}
catch (...)
{
cout << "Unkowned exception" << endl;
}
}
return 0;
}
异常安全问题
1.异常抛出后,后面的代码就不再执行,如果前面申请了资源,后面进行释放,中间抛异常会导致资源得不到释放,引发资源泄露,一种解决方法是捕获异常时释放资源再重新抛出,另一种是使用智能指针(之后文章会写)。
2.其次在析构函数中,如果抛出异常也要谨慎处理,⽐如析构函数要释放10个资源,释放到第5个时抛出异常,也需要捕获处理,否则后⾯的5个资源没释放,就会资源泄漏。
例:
class Exception
{
public:
Exception(const string& errmsg, int id)
:_errmsg(errmsg)
, _id(id)
{
}
virtual string what() const
{
return _errmsg;
}
int getid() const
{
return _id;
}
protected:
string _errmsg;
int _id;
};
double fun10(double a, double b)
{
if (b == 0)
throw Exception("0不可除", 666);
return a / b;
}void fun11()
{
double* num = new double[10];for (int i = 0; i < 10; i += 2)
{
try
{
cin >> num[i] >> num[i + 1];
cout<<fun10(num[i], num[i + 1])<<endl;
}
catch (...)
{
cout << "delete[] num" << endl;
delete[] num;
throw;//捕到什么抛什么
}
}delete[] num;
}int main()
{
try
{
fun11();
}
catch (const Exception& e)
{
cout << e.what() << endl;
}
catch (...)
{
cout << "Unkowned exception" << endl;
}
return 0;
}
异常规范
1.对于用户和编译器而言,预先知道某个程序/某个函数会不会抛异常对代码的简化起到不小作用。
2.C++11中选择在函数参数列表后加noexcept表示不会抛出异常,啥都不加表示可能抛出异常。
3.编译器并不会在编译时检查noexcept,也就是说如果⼀个函数⽤noexcept修饰了,但是同时⼜包 含了throw语句或者调⽤的函数可能会抛出异常,编译器还是会顺利编译通过的(有些编译器可能会 报个警告)。但是⼀个声明了noexcept的函数抛出了异常,程序会调用terminate 终⽌程序。
4.noexcept(expression)还可以作为⼀个运算符去检测⼀个表达式是否会抛出异常,可能会则返回 false,不会就返回true。
注:只要函数后加了noexcept,用noexcept检查只会返回true
小知识
1.auto是占位符,在编译阶段,推演出初始化表达式的实际类型来替换auto位置
2..在C++98中,new单个int类型空间可以直接初始化,new一段连续int类型空间不能直接初始化