C + + exception handling

Source: Internet
Author: User

Overview

Today listen to the project group of C + + experts speak C + + exceptions, benefited. Sure enough, with the master can learn more things. Below I will introduce this expert C + + exception handling to share to the garden of Bo friends.

What is an exception?

In programming languages, there are errors at the time of the error, and there are compile-time errors and run-time errors.

Compile-time errors you must be familiar with it, and when we build a program, the error hints that appear in the console are compile-time errors. These errors can be checked by the compiler at compile time.

Run-time errors you may not see very often, because the program you write is often run in the "Greenhouse", and rarely see the situation of the program crashes. There are many kinds of runtime errors, for example, when we want to request memory on the heap, there is not enough memory space, or when the file is created, there is not enough disk space, these are run-time errors. We use a name-exception to call this run-time error.

How does C + + catch exceptions?

C + + has its own exception handling system, and its syntax for catching exceptions is similar to Java and C #, and can be seen in the following code:

1 intMain () {2 3     Try{4cout<<"This is the easy exception example."<<endl;5         Throw 1;6}Catch(inti) {7cout<<"catched the EXCEPTION:I ="<<i<<endl;8}9 Ten     return 0; One}

The syntax is simple, with a try block to contain the code to catch the exception area, the code will throw an exception, and then catch to catch the exception, the output of the above code is as follows:

1 Please press any key to continue ...

Use catch (...) with caution.

C + + Exception capture provides a universal trap, which is a catch (...) that captures arbitrary exceptions, as you can see, because there are no parameter names, so we can't get the content passed by the exception. But there is another important problem, that is catch (...) Location problem. Here's a look at the code:

1     Try{2cout<<"This is the easy exception example."<<endl;3         Throw 1;4}Catch(...) {5cout<<"catched the exception."<<endl;6}Catch(inti) {7cout<<"catched the EXCEPTION:I ="<<i<<endl;8}

The above code puts the catch (...) Before I put it in catch (int i), what's the problem? catch (int i) contains exception handling blocks that are never executed. A bit tougher compilers will point out errors for us, but some compilers are less powerful. So, remember a rule: catch (...) Always put to the last of all catch catch processing.

Using classes in the inheritance system as parameters of catch

This problem is similar to the above problem and is also the catch priority problem, see the following code:

1     Try{2DerivedClass DC;3cout<<"This is the easy exception example."<<endl;4         Throwdc5}Catch(Superclass s) {6cout<<"catched the Exception:superclass."<<endl;7}Catch(DerivedClass D) {8cout<<"catched the Exception:derivedclass."<<endl;9}

In the above code, we throw the object of the DerivedClass class, which we thought would go into the processing block of catch (DerivedClass D), but in fact it calls the processing block of catch (superclass s). This code compiler does not check, we can only rely on ourselves, remember a criterion: to put the highest level of the parent class in the last catch to deal with.

Three occasions when an object destructor is called?

When will the object destructor be called? First, there are three scenarios in which destructors are called. What are the three kinds? Let's look at two familiar types:

1 void func () {2     a A;  3 }

The first: When the function is called, the destructor for object A of a is automatically called when the function completes the call.

1     New A (); 2     Delete A;

The second: The called DELETE statement that is displayed also invokes the object's destructor.

What's the third thing? In fact you have seen, is the exception processing area of the throw statement, see the following code:

1     Try {2         DerivedClass DC; 3         cout<<"This a easyexception example. "<<endl; 4         throw DC; 5     }

The above code, the throw statement actually calls a destructor for us, although there may be statements behind the function. In fact, when an object is thrown, the exception system has copied a Tem_dc object. Then call DerivedClass's destructor. So, the following code makes us feel very annoyed:

1     Try {2         New DerivedClass (); 3         throw the pDc; 4     }

We want to throw out the object that the PDC points to, in fact we just throw the PDC pointer, and the object has already been refactored. So here's a guideline: try not to throw pointers and references.

Do not send hope and type conversions in the exception handling system

Do not expect the exception handling system to complete the type conversion for us, see the following code:

1     Try {2         Throw ' a '; 3     } Catch (int ch) {4         cout<<"This isa ch"<<endl;  5     }

Usually write code, the ' a ' can be converted to ASIC code value, but this time is not, the program run time is wrong. So, remember a guideline: Don't expect the C + + exception handling system to help you with type conversions.

Is there anything that the C + + exception handling system can't capture?

Yes, but no, what do you mean? It was, but it was settled. I don't know if you remember the member initialization list of C + +, if you don't remember, let's look at the following code:

1 classtest{2 Private:3     intAge4  Public:5Test (): Age (Initialze (1)){6     7}8     intInitialze (inti) {9         if(i = =1){Ten             Throw 1; One}Else{ A             return 1; -} -} the};

In the above code, the constructor calls the initialize function that could throw an exception in the member initialization list, so how is the exception captured? In the words of a predecessor: C + + provides a very ugly syntax to solve this problem. How to solve it? Look at the following code:

1     Test ()2     try: Age (Initialze (1)) {3         {4             ///  function Body 5         }6     }catch(int i) {7         cout< <"exception"<<endl; 8     }

is not very ugly grammar, I also think how good-looking, but did catch the member initialization list of exceptions.

The usefulness of the set_unexpected function

The function, in short, is to set the default exception handling function. What do you mean? See the code below to find out.

1 voidMyFunc () {2cout<<"set_unexpected Exception."<<endl;3     Throw 0;4}5 voidFunintXThrow(Char)6{7     Throw 'a';8}9 intMain () {Tenset_unexpected (MyFunc); One     Try{ AFun1); -}Catch(inti) { -cout<<"int Exception"<<endl; the} -  -System"Pause"); -     return 0; +}

Starting from main, we have registered a default exception handler, which makes a correction to the exception. The fun function throws a char exception, our statement is not captured, so after the default processing function correction, it can be caught with catch (int i).

However, the above code is not working on VS, and running on Linux is okay.

Effective C + +: Do not let exceptions escape destructors

Read the above, you are already very good, of course, this is just a joke. There is one in effiectivec++: Do not let an exception escape the destructor. What do you mean? is when we encounter the following code:

1     try{2         derivedclass dc;3         cout<< "This a easy exception example." <<endl;4         throw dc;5     }catch (superclass s) {6         cout<< "catched the Exception:superclass." <<endl;7     }catch (derivedclass d) {8         cout<< "catched the Exception:derivedclass." <<endl;9     }

After the above code throws the DC, the destructor of DerivedClass is called, so that if the destructor is thrown again, our capture function does not know what to do with the tragedy. That is, the program will simply go down after the two throw exceptions are present. So, do not let the exception escape the destructor, otherwise, you are tragic.

C + + exception handling

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.