64、c++异常处理(上)

c++内置了异常处理的语法元素try...catch

try语句处理正常的代码逻辑

catch语句处理异常情况

try语句中的异常由对应的catch语句处理

c++通过throw语句抛出异常信息:

c++异常处理分析:throw抛出的异常必须被catch处理,当前函数能够处理异常,程序继续往下执行。当前函数无法处理异常,则函数停止执行,并返回(没有返回值)。

未被处理的异常会顺着函数调用栈向上传播,直到被处理为止,否则程序将停止执行。

function1->function2->function3(throw1)

3中的异常不能处理的话,3函数停止并返回函数2,函数2不能处理的话,立即停止返回函数1,如果一直被处理,程序异常停止执行。

#include <iostream>
#include <string>
using namespace std;
double divide(double a, double b)
{
    const double delta = 0.000000000000001;
    double ret = 0;    
    if( !((-delta < b) && (b < delta)) )
    {
        ret = a / b;
    }
    else
    {
        throw 0;   //(带着异常返回到上一函数,即调用他的函数main())
    }    
    return ret;
}
int main(int argc, char *argv[])
{    
    try
    {
        double r = divide(1, 0);            
        cout << "r = " << r << endl;
    }
    catch(...)
    {
        cout << "Divided by zero..." << endl;
    }   
    return 0;
}

同一个try语句可以跟上多个catch语句,catch语句可以定义具体处理的异常类型。不同类型的异常由不同的 catch 语句负责处理,try语句中可以抛出任何类型的异常。catch(...)用于处理所有类型的异常。任何异常都只能被捕获(catch)一次。

异常处理的匹配规则:

异常抛出后,至上而下严格匹配每一个catch语句处理的类型。

try{throw 1;}

catch(Type1 t1){}

catch(Type2 t2){}

catch(TypeN tn){}

异常处理匹配时,不进行任何类型转换。

#include <iostream>
#include <string>
using namespace std;
void Demo1()
{
    try
    {   
        throw 'c';
    }
    catch(char c)
    {
        cout << "catch(char c)" << endl;
    }
    catch(short c)
    {
        cout << "catch(short c)" << endl;
    }
    catch(double c)
    {
        cout << "catch(double c)" << endl;
    }
    catch(...)   //只能放到最后的地方,不能放到其他catch之前
    {
        cout << "catch(...)" << endl;
    }
}
void Demo2()

{

  //  throw “D.tshogn”;      //const char*

    throw  string ("D.tshogn");

}

int main(int argc, char *argv[])
{    
    Demo1();    
    try
    {
        Demo2();
    }
    catch(char* s)
    {
        cout << "catch(char *s)" << endl;
    }
    catch(const char* cs)
    {
        cout << "catch(const char *cs)" << endl;
    }
    catch(string ss)
    {
        cout << "catch(string ss)" << endl;
    }    
    return 0;
}

从上到下严格匹配,c++中直接支持异常处理的概念,try...catch...是c++中异常处理的专用语句,try语句处理正常代码逻辑,catch语句处理异常情况,同一个try语句可以跟上多个catch语句,异常处理必须严格匹配,不进行任何的类型转换。

猜你喜欢

转载自blog.csdn.net/ws857707645/article/details/80291733