Monday, March 26, 2012

exception rethrow


#include <iostream>

struct A{

  A(){std::cout<<"new A @"<<this<<std::endl;}
  ~A(){std::cout<<"bye A @"<<this<<std::endl;}

  virtual void rethrow(){
    throw *this;
  }

};

struct B:public A{

  B(){std::cout<<"new B @"<<this<<std::endl;}
  ~B(){std::cout<<"bye B @"<<this<<std::endl;}

  virtual void rethrow(){
    throw *this;
  }


};

void handle(A& a){
  try{
    a.rethrow();
  }catch(B& b){
    std::cout<<"hey a B:"<<&b<<std::endl;
  }catch(A& a){
    std::cout<<"hey an A"<<&a<<std::endl;
  }
}


int main(){

  try{  
    try{
      throw B();
    }catch(A& a){
      handle(a);
      throw;
    }
  }
  catch(B& b){
    std::cout<<"a B:"<<&b<<std::endl;
  }

  catch(A& a){
    std::cout<<"an A:"<<&a<<std::endl;
  }
 

}

=====out=====

new A @0xea8090
new B @0xea8090
hey a B:0xea8120
bye B @0xea8120
bye A @0xea8120
a B:0xea8090
bye B @0xea8090
bye A @0xea8090




No comments:

Post a Comment