代码规范_3:c++ _异常

http://www.cnblogs.com/nzbbody/p/3418989.html

  • 指针和动态分配导致的内存回收问题:在C++中,不会自动回收动态分配的内存,如果遇到异常就需要考虑是否正确的回收了内存。

捕获异常

  • 抛出异常用throw,捕获用try……catch。
//throw造成程序执行过程中从oz()函数返回时,对象rb的析构函数调用
#include <iostream>
using namespace std;

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

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

int main()
{
   try{
      cout<<"tornado,witch, munchkins ..." <<endl;
      oz();
   }  catch(int){
      cout << "Auntie Em! I had the strangest dream ..."<<endl;   
   }
}

异常匹配

  • 通过引用而不是值来匹配异常
//不会将一种异常转换为另一种异常
#include <iostream>
using namespace std;

class Except1{};

class Except2{
public:
   Except2 (const Except1 &) {}
};

void f() {throw Except1();}

int main()
{
   try{
      f();
   }catch (Except2&){
      cout<< "inside catch(Except2)"<<endl;
   } catch (Except 1&){
      cout<< "inside catch(Except1)"<<endl;
   } 
}

//输出结果:Except1
不可以将Except1转换为Except2
  • 基类捕获派生类
#include <iostream>
using namespace std;

class x{
  public:
    class Trouble {};
    class Small : public Trouble{};
    class Big: public Trouble{};
};

int main()
{
   X x;
   try{
      x.f();
   } catch(X::Trouble &){
     cout<< "caught Trouble" <<endl
   } catch(X::Small&){
     cout<< "Caught Small Trouble"<<endl;
   } catch(X:: Big &){
     cout<< "caught Big Trouble"<<endl;
   }
}

//将Trouble对象,或者派生自Trouble的对象(small 或者 big)匹配到第一个异常

//通常,捕获派生类的异常,最后捕获

捕获所有异常

  • catch( … )

清理

  • 当程序离开一个作用域时,由构造函数构造的对象,一定会调用析构函数析构

资源

  • 当构造函数执行中抛出异常,那么对象的析构函数就不会被调用

auto_ptr

  • 封装堆内存的指针

标准异常

你可能感兴趣的:(代码规范_3:c++ _异常)