C++中异常处理的工作方式

来源:互联网 发布:训练口语的软件 编辑:程序博客网 时间:2024/05/22 04:26

#include <iostream>
using namespace std;

class Rainbow{
public:
 Rainbow(){cout << "Rainbow() " << endl;}
 ~Rainbow() { cout << "~Rainbow()" << endl; }

};

void oz(){

 Rainbow rb;
 for(int i = 0; i < 3; i ++){
  cout << "There is no place like home " << endl;
 }
 
 throw 47;

 throw 11.12f;
 
 cout << "Function continues after throw..." << endl;
}

void main(){

 try{
  cout << "tornado, witch, munchkins, ..." << endl;
  oz();

  cout << "try continues after handle the throw..." << endl;
 } catch (int) {
  cout << "Auntie Em! I had the strangest dream..."
   << endl;
 } catch (float) {
  cout << "Catch a float exception" << endl;
 }

 cout << "Main function continues after handling the exception" << endl;
 
}

 

输出结果如下:

tornado, witch, munchkins, .

Rainbow()

There is no place like home

There is no place like home

There is no place like home

~Rainbow()

Auntie Em! I had the strangest dream.

Main function continues after handling the exception

 

以上的输出说明:

没有输出Function continues after throw...说明,在抛出异常之后函数就已经结束,不会再继续向下执行

没有输出try continues after handle the throw...说明在try块中,遇到一个异常后try块中之后的语句也将不再执行,所以之后的异常也不会被检测到;

没有输出Catch a float exception说明在异常处理块中,捕捉到第一个异常之后就会结束之后的catch块处理语句将不会再执行

输出Main function continues after handling the exception说明在try--catch块后程序将按照代码流程一次顺序执行

~Rainbow()输出在Auntie Em! I had the strangest dream之前,说明在抛出异常时候是先进行了数据清理,然后再进行的是数据异常的处理工作

原创粉丝点击