前言
早在c语言的时候,就已经有处理错误的方式了,第一种方式太过暴力,就是断言,程序发生错误,直接终止退出,这样的报错对于真正开发应用等太过暴力。第二种方式,就是返回errno,其实,我们会在发生错误的时候,或者程序结束运行的时候,返回一个错误码,错误码就是一个数字,不同的数字的错误码表示的错误信息也不一样,c语言种就是用errno表示这些错误码。
但这两种方式在处理错误上不是比较好,因此c++就引入了异常,用来处理错误。
异常
异常的抛出与捕获机制
未知异常
抛子类异常捕获父类异常
异常的重新抛出
异常的安全问题
异常的规范
异常
throw: 当问题出现时,程序会抛出一个异常。这是通过使用 throw 关键字来完成的。catch: 在您想要处理问题的地方,通过异常处理程序捕获异常 . catch 关键字用于捕获异常,可以有多个 catch 进行捕获。try: try 块中的代码标识将被激活的特定异常 , 它后面通常跟着一个或多个 catch 块。如果有一个块抛出一个异常,捕获异常的方法会使用 try 和 catch 关键字。 try 块中放置可能抛 出异常的代码,try 块中的代码被称为保护代码。
例如下面的简单例子:
double Divsion(int x, int y)
{if (y == 0){//如果分母为零,我们就可以抛异常,这里抛得东西可以是任意类型的对象throw "除零错误";}else{return (double)x / y;}}
int main()
{try{int x = 1.1; int y = 0;double ret = Divsion(x,y);}catch (const char * x) //捕获异常,并打印异常的错误信息{cout << x<<endl;}return 0;
}
注意:1.抛异常可以是任意类型的对象,不捕获异常也会报错(无具体的错误信息).2.可以在任意地方捕获异常(任何一个函数栈帧),一般是在调用的哪里捕获。
重点 3.捕获异常的类型必须与抛出异常的类型一致,否则无法捕获。
程序在运行的过程中在遇到这里的异常后会立马就会跑到捕获异常的代码处,捕获之后正常继续执行, 若没抛异常则会跳过try catch语句。
异常的抛出与捕获机制
1. 异常是通过抛出对象而引发的,该对象的类型决定了应该激活哪个catch的处理代码。2. 被选中的处理代码是调用链中与该对象类型匹配且离抛出异常位置最近的那一个。3. 抛出异常对象后,会生成一个异常对象的拷贝,因为抛出的异常对象可能是一个临时对象,所以会生成一个拷贝对象,这个拷贝的临时对象会在被catch以后销毁。(这里的处理类似于函数的传值返回)4. catch(...)可以捕获任意类型的异常,问题是不知道异常错误是什么。5. 实际中抛出和捕获的匹配原则有个例外,并不都是类型完全匹配,可以抛出的派生类对象, 使用基类捕获,这个在实际中非常实用。
1. 首先检查throw本身是否在try块内部,如果是再查找匹配的catch语句。如果有匹配的,则调到catch的地方进行处理。2. 没有匹配的catch则退出当前函数栈,继续在调用函数的栈中进行查找匹配的catch。3. 如果到达main函数的栈,依旧没有匹配的,则终止程序。上述这个沿着调用链查找匹配的catch子句的过程称为栈展开。所以实际中我们最后都要加一个catch(...)捕获任意类型的异常,否则当有异常没捕获,程序就会直接终止。4. 找到匹配的catch子句并处理以后,会继续沿着catch子句后面继续执行。
例如:
class Func
{
public:void test(){cout << "Func for test";}
};
double Divsion(int x, int y)
{if (y == 0){//如果分母为零,我们就可以抛异常,这里抛得东西可以是任意类型的对象throw "除零错误";}else{return (double)x / y;}//若有抛出异常,则在捕获异常时Func a;
}
void Test()
{Func a;//在捕获时,优先走栈链最近的哪一个,这里就走test里的,而不走main中的try{int x = 1.1; int y = 0;double ret = Divsion(x, y);}catch (const char* x){cout << x << endl;}a.test();
};
int main()
{Test();try{int x = 1.1; int y = 0;double ret = Divsion(x,y);}catch (const char * x){cout << x<<endl;}//如果都走到mian这里,且走完了,也没有发现有捕获的,依然会报错return 0;
}
综上可得:异常的捕获会引发执行流的跳跃。
在抛出异常时,会自动生成抛出异常的临时拷贝,到了捕获时,传给他。
未知异常
double Division(int a, int b)
{// 当b == 0时抛出异常if (b == 0){throw "Division by zero condition!";} elsereturn ((double)a / (double)b);
}
void Test()
{throw string("test");
}
void Func()
{int len, time;cin >> len >> time;cout << Division(len, time) << endl;
}
int main()
{try {Func();}catch (const char* errmsg){cout << errmsg << endl;}try{Test();}catch (...) {cout << "unkown exception" << endl;}return 0;
}
抛子类异常捕获父类异常
实际服务器开发中的异常体系,首先会写一个父类,通常包含异常信息message和异常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){Sleep(10);try {HttpServer();}catch (const Exception& e) // 这里捕获父类对象就可以{// 多态cout << e.what() << endl;}catch (...){cout << "Unkown Exception" << endl;}}return 0;
}
异常的重新抛出
void Func()
{throw string("test");
}
void Test()
{//假设在此之前我们有一个数组int* arry = new int[10];Func();delete[]arry;arry = nullptr;cout << "arry has reliszed";
}
int main()
{try{Test();}catch (string str){cout << str << endl;}
}
void Func()
{throw string("test");
}
void Test()
{//假设在此之前我们有一个数组int* arry = new int[10];//在该位置,再次进行捕捉,并抛出try{Func();}catch (string str){cout << str << endl;delete[]arry;arry = nullptr;cout << "arry has reliszed";throw;}}
int main()
{try{Test();}catch (string str){cout << str << endl;}
}
异常的安全问题
异常的规范
对于需要抛异常的,我们在函数后面列出可能会抛出的类型。
对于不用抛异常的,c++提供了关键字noexcept,在函数体后面添加noexcept表示不会有异常,但我们要确保没有异常。
若函数体没有任何声明,则可能会抛出各种异常。
事实上在这里声明可能会抛出的异常的类型,并不是很准确的,我们声明只有一种类型,但也可以抛别的异常,不过c++规范我们去使用异常,确信会抛出哪些异常,我们就在函数后面声明。
// 这里表示这个函数会抛出列出中的某种类型的异常
void fun() throw(A,B,C,D);// 这里表示这个函数只会抛出bad_alloc的异常
void* operator new (std::size_t size) throw (std::bad_alloc);// C++11 中新增的noexcept,表示不会抛异常
thread() noexcept;
thread (thread&& x) noexcept;
异常的使用有缺点也有优点,但运用起来利大于弊。