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
points
1.1 the class type of the exception must support copy
1.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;
}
output
destruction b
destruction a
exception raise
release all the object before the exception raised
3. 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