c++异常处理

来源:互联网 发布:程序员薪资2017 编辑:程序博客网 时间:2024/06/05 18:41

c++异常处理机制由三个部分组成:检查(try),抛出(throw),和捕捉(catch)

  1. 首先把可能出现异常的,需要检查的语句或者程序段放在try后面的花括号中
  2. 程序开始运行后,按正常的顺序执行到try块,执行try块中花括号内的语句。如果在执行try块内的语句过程中没有发生异常,则try-catch结构中的catch字句不起作用,流程转到catch字句后面的语句继续执行。
  3. 如果在执行try块内的语句过程中发生异常,则throw语句抛出一个异常信息,执行了throw语句后,流程立即离开本函数,转到其上一级的函数。
  4. 这个异常信息提供给try-catch结构,系统会寻找与之匹配的的catch子句
  5. 在进行异常处理后,程序并不会自动终止,继续执行catch子句后面的语句。

下面是示例代码

#include <iostream>#include <cmath>using namespace std;double area_triangle(double a,double b,double c);//声明面积计算函数int main(){    double a,b,c;    cin>>a>>b>>c;    try    {         while(a>0&&b>0&&c>0)        {        cout<<"area is:"<<area_triangle(a,b,c)<<endl;        cin>>a>>b>>c;        }    }   catch(...)   {     cout<<"This is Not a Trisngle"<<endl;   }    cout << "Hello world!" << endl;    return 0;}double area_triangle(double a,double b,double c){if(a+b<=c||b+c<=a||a+c<=b) throw a;//检测是否正常,异常则抛出double s=(a+b+c)/2;return sqrt(s*(s-a)*(s-b)*(s-c));}