Coding Road--Re-learning C + + (9): Resolving Exceptions

Source: Internet
Author: User

1. What is an exception

(1) The basic idea of the anomaly is to let a function find itself unable to solve the error when throwing an exception, let the caller to solve. Exception handling mechanism is similar to compile-time type checking and ambiguity control at runtime counterpart, it is a non-local control structure, when throwing an exception, we use the stack fallback to find the upper function that can handle the exception. Some people think of an anomaly as a big, irreparable mistake in the program, but the exception usually means "some part of the system can't do what it's going to do".

(2) When we catch an exception with catch, we initialize the parameter with the value of the actual argument, which may cause our thrown exception to be cut because of the catch, so we often use pointers and references to catch exceptions to ensure the integrity of the exception information.

(3) We need to know that when an exception is thrown, it is copied, and the processor gets just a copy of the exception. In general, when all exceptions cannot be resolved in a handler function, we will re-throw the exception and let the exception be handled in the appropriate place. Note that no matter if the exception is not cut when we catch the exception, the exception we re-throws is always the original type when the exception was first thrown.

2. Resource Management

(1) The application of resources is initialized. How to properly request resources and release resources is a very important problem in programming, generally we use objects with constructors and destructors to handle the request and release of resources, because when we throw an exception, we make a stack fallback ("Go up through the stack" to find the corresponding processor for an exception). At this point all the constructed local objects call the destructor, which guarantees the correct release of the resource.

class file_ptr{    *p;  Public :    FILE_PTR (constcharconstchar *a) {p = fopen (n, a);}     *PP) {p = pp;}     ~file_ptr () {fclose (P);}     operator File* () {return  p;}};

The most common resource for this use is storage, but may result in "storage churn":

class y{    int *p;     void init ();  Public :    Y (intnewint[s]; init ();}     ~Y () {delete [] p;}};

If Init () throws an exception, the construction of the related object is not completed and the destructor is not called, and the allocated storage is not freed. A safe variant is:

class z{    vector<int> p;     void init ();  Public :     Z (int  s):p (s) {init ();}      // ...};

(2) Smart pointer auto_ptr. AUTO_PTR supports the "resource request as initialization" technique, and auto_ptr has the same replication semantics as a regular pointer: After the auto_ptr is copied to another, the original auto_ptr will no longer point to anything. Because replication of auto_ptr requires modifications to itself, Const AUTO_PTR cannot replicate, and Auto_ptr's destructive replication also makes it not satisfy standard containers and standard algorithms. Auto_ptr stated in <memory>, described below:

template<classX>classstd::auto_ptr{Template<classY>structauto_ptr_ref{/*...*/};//Auxiliary ClassesXptr; Public: typedef X ELEMENT_TYPE; ExplicitAuto_ptr (X *p =0)Throw() {ptr =p;} ~auto_ptr () {delete ptr;} //Note that the copy constructor and assignment are used with non-const parameters//The following 4 are all copied first, then a.ptr=0Auto_ptr (auto_ptr &a)Throw(); Template<classY> auto_ptr (auto_ptr<y> &a)Throw(); Auto_ptr&operator= (auto_ptr &a)Throw(); Template<classY>auto_ptr&operator= (auto_ptr<y> &a)Throw(); X&operator*()Const Throw(){return*ptr;} X*operator()Const Throw() {returnptr;} X*Get()Const Throw{returnPTR;}//Extracting pointersx* release ()Throw() {X *t = Ptr;ptr =0;returnt;}//Waiver of Ownership     voidReset (X *p =0)Throw(){         if(P! = PTR) {delete ptr; ptr =p;} } auto_ptr (Auto_ptr_ref<X>)Throw();//Copy from Auto_ptr_reftemplate<classY>operatorAuto_ptr_ref<y> ()Throw(); Template<classY>operatorAuto_ptr<y> ()Throw();};

(3) New and abnormal. The following is a simple implementation of the operator new for the standard library:

void operator New (size_t size) {    for(;;) {        if(voidreturn  p;         if 0 Throw Bad_alloc ();        _new_handler ();    }}

When operator new does not find storage, it calls the _new_handler function to find the right space, and if it is not found, only throws an exception. _new_handler is a function pointer. Generally if you want to make your defined function a _new_handler (), you need to call the Set_new_handler function, and the Set_new_handler function receives a pointer of type void (*p) ().

(4) Unexpected exception. If we encounter unexpected mappings, we can throw bad_exception with the std::unexcepted () function. It is set by the set_unexcepted function.

(5) An exception that is not caught. If an exception is not captured, the Std:terminate () function is called, which is set by the Std::set_terminate () function.

3. Declaration of the exception.

(1) The Declaration of the exception clearly tells us what exception the function throws, and the exception declaration belongs to the interface, and you can know the exception thrown when the specific implementation of the function is not known.

(2) If a function has a declaration that contains an exception description, the exception description for each declaration of the function is consistent.

(3) To overwrite a virtual function, the description of the exception with the function must be at least as restrictive as the exception description of that virtual function.

classb{ Public:        Virtual voidf (); Virtual voidG ()Throw(X, Y); Virtual voidH ()Throw(X);};classD: Publicb{ Public:        voidF ()Throw(X);//OK    voidG ()Throw(X);//Yes, d::g () is more constrained than b::g ()    voidH ()Throw(X, Y);//error, D::h () No more than b::h () Limited};

The same is true for function pointers, which you can assign to a less restrictive function pointer with a more restrictive function pointer. Therefore, you cannot assign a function pointer with an exception description with a function pointer that does not have an exception description. In addition, you cannot have an exception description when using a typedef on a function pointer, because the exception description is not part of the function type.

(3) No exception description represents a function that can throw any exception, and throw () represents a non-throwing exception.

Coding Road--Re-learning C + + (9): Resolving Exceptions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.