异常处理

异常处理是程序中非常重要的一环,c++也不例外,C++处理异常的机制由三个部分组成:检查(try)、抛出(throw)和捕捉(catch)。 

把需要检查的(你所不放心的、认为可能会出现异常的)语句放在try中;

throw用来抛出异常信息,一般throw都是在try中的,当然也可以放在其他地方;

catch用来捕捉throw抛出的异常信息。

注意:

  • catch一定是紧跟在try之后的,中间不能有其他语句,当然也可以不要catch语句。
  • catch接受的参数往往是一种类型,如int或者double,catch只会匹配throw信息的类型,而不会匹配具体值。
  • throw之后最多被一个catch捕获,其他catch就不会再捕获了。
  • catch可以接受...作为参数,这样,对于一些没有捕获到的异常,都会通过这个catch代码块捕获,且需要放在最后。

例1:

#include <iostream>
#include <cmath>
using namespace std;
double jie(double a, double b, double c);
int main()
{
  cout << "begining" << endl;
  double a, b, c, aa;
  cout << "Pleasse input a, b, c:";
  cin >> a >> b >> c;
  try
  {
    aa = sqrt(jie(a, b, c));
    cout << "x1=" << (-b + aa) / (2 * a) << endl;
    cout << "x2=" << (-b - aa) / (2 * a) << endl;
  }
  catch (double)
  {
    cout << "a=" << a << endl << "this is not fit for a" << endl;
  }
  catch (const char *s)
  {
  cout << s << endl << "this is not fit for a,b,c" << endl;
  }
  catch (...)
  {
    cout << "all error is not good" << endl;
  }
  return 0;
}
double jie(double a, double b,double c)
{
  double disc;
  if (a == 0) throw 0;
  else if ((disc = b * b - 4 * a * c) < 0) throw "b * b - 4 * a *c < 0";
  else return disc;
}

以上就是一个典型的try-throw-catch异常处理系统,这样,即使输入的数据有误,也可以顺利执行,而不会造成程序强制退出的情况。

例2:

#include <iostream>
using namespace std;
int main()
{
    void fun1();
    try
    {
        fun1();
    }
    catch (double)
    {
        cout << "OK0" << endl;
    }
    cout << "end0" << endl;
    return 0;
}
void fun1()
{
    void fun2();
    try
    {
        fun2();
    }
    catch (char)
    {
        cout << "OK1" << endl;
    }
    cout << "end1" << endl;
}
void fun2()
{
    double a = 0;
    try 
    {
        throw a;
    }
    catch (float)
    {
        cout << "OK2" << endl;
    }
    cout << "end2" << endl;
}

通过运行,可以得到结果: 

OK0
end0

解释:从main开始执行,执行fun1,进入fun1,执行fun2,fun2直接抛出一个 double类型 的错误,首先在fun2中寻找相应catch,无double类型catch,返回上一级,在fun1中寻找相应catch,找不到继续返回到main中,匹配到double类型的catch,于是输出OK0,再输出end0,此程序运行结束。

假设我们将fun2函数中的catch块改为:

catch(double) { cout << "OK1" << endl; }

这样,最终的输出结果如下:

OK2
end2
end1
end0

解释:从主函数到fun1到fun2,抛出错误,于是在fun2中寻找相应catch,匹配后,其他catch无效,并且输出OK2,继而end2,然后返回到fun1中,由于错误已经捕获,所以执行后面的输出end1,接着回到main中,输出end0。

可以看到:这种方式和JavaScript中的作用域链是类似的。 

原文地址:https://www.cnblogs.com/zhuzhenwei918/p/8566856.html