Exception C++

来源:互联网 发布:淘宝怎么进自己店铺 编辑:程序博客网 时间:2024/06/01 13:28
When we talk about the mechanism of  exception in C++,we mainly care about the following points.1. thow the class type exception or pointer type exception   in object oriented  programm,we choose to throw a exception object instead of build-in type.we should never lose the following points1.1 the class type of the exception must support copy1.2 a pointer type must point to a object which should exsist when we call catch.2. the conception of stack unwinding  2.1 when call some function which raise the exception,appication will stop this function. checking weather  throw is in try sentince. if in find the catch and handle. else search in the function which call this function.  2.2 when function raise the exception,this function terminal firstly then search the try catch. this means firstly free the memory and do the destruction of the local object.  2.3 remember Just free the local store variant.when you use the malloc or new,those memory never be free. class A{public:A(const string str):m_str(str){}~A(){cout<<"destruction  "<<m_str<<endl;//throw m_str + "raise";}string m_str;};void my_terminal(){cout<<"terminal"<<endl;}int _tmain(int argc, _TCHAR* argv[]){set_terminate(my_terminal);try{        A a("a");A b("b");throw "excetion raise";A c("c");}catch(const char* str) {cout<<str<<endl;}getchar();return 0;}outputdestruction  bdestruction  aexception raiserelease all the object before the exception raised3. never try to raise a excaption in destruction of the object   see the follow code   try   {     A a;     A b;    }    catch   {       }   class A's destruction can raise a exception.when b is destroyed,a exception raised. then call a's destruction function not catch.   at this time two exception which never be handled raised. C++ can't handle this problem. Application will auto call for terminal() abort()funtion 4. the way to handle the exception with the relationship of inherit
 带有因继承而相关的类型的多个catch字句,必须从最低派生类型,到最高派生类型。catch参数可以定义为引用不必复制,或者非引用的形参基类的异常说明符可以捕获子类的异常类型。

原创粉丝点击