我们平时写完代码运行的过程中,会出现一些问题,但是又不想让程序立马挂掉,或者有些数据没有处理程序就终止运行了。
对于不想让程序直接遇到问题就停止的情况,我们可以用try...catch...捕获异常,打印出异常后继续运行。对于有些数据没有处理程序就挂掉的情况,我们可以用c++的析构函数和java中的finally来进行处理。
- throw: 当问题出现时,程序会抛出一个异常。这是通过使用 throw 关键字来完成的。
- catch: 在您想要处理问题的地方,通过异常处理程序捕获异常。catch 关键字用于捕获异常。
C++ 提供了一系列标准的异常,定义在<exception>中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的,如下所示:
表是对上面层次结构中出现的每个异常的说明:
代码示例:
#include <iostream>
#include <stdexcept>
#include <vector>
#include <string>
using namespace std;
class Test {
public:
int a;
int b;
Test(int a, int b) {
this->a = a;
this->b = b;
}
double division() {
if (b == 0) {
throw "Division by zero condition!"; //自定义抛出的异常
}
return (a/b);
}
~Test() { //此函数为析构函数,异常发生后,该函数会被执行,相当于java中的finally
cout<<"this func will be exec finally"<<endl;
}
};
int main ()
{
int x = 50;
int y = 0;
double z = 0;
Test test(x, y);
try {
z = test.division();
} catch (const char* msg) { //捕获异常
cerr << msg << endl;
}
try {
z = test.division();
} catch (...) { //三个点表示可以捕获任意类型的异常
cerr << "there is an error" << endl;
}
vector<int> v(10);
try {
v.at(100) = 100; //拋出 out_of_range 异常
}
catch (out_of_range & e) {
cerr << e.what() << endl;
}
string s = "hello";
try {
char c = s.at(100); //拋出 out_of_range 异常
}
catch (out_of_range & e) {
cerr << e.what() << endl;
}
return 0;
}
总结:
- c++的析构函数相当于finally的作用;
- c++的异常捕获使用并不灵活,需要提前知道会发生哪些异常再进行定义。