C++primer_ Notes _ Exception Handling

Source: Internet
Author: User

exception , throws an exception when a function finds an unhandled error, letting the function's

The caller handles the problem directly or indirectly.

exception Handling , which allows two independently developed program components to encounter programs that are not normal during program execution

Conditions (known as exceptions, exception) are mechanisms for communicating with each other.

exception throws:

throw (expression)

Exception discovery and throw exception:

/* Find exception and throw exception */try{//statement with possible exception}

Catching Exceptions:

catch (type name + formal parameter name)//catch specific type exception {}
catch (...) Captures any type of exception (used when the exception type is not determined) {}

Down to see a simple example:

#include <iostream>using namespace Std;int Div (int a, int b) {return a/b;}    int main () {Div (1,0);    System ("pause"); return 0;}

The results show:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/7E/96/wKiom1cE0VOjWHJzAABAUomO4h0197.png "title=" KY) ZY} ' 2j7djk6aq1}kx@xd.png ' alt= "Wkiom1ce0vojwhjzaabauomo4h0197.png"/>

The program crashes directly, because the invocation of the second parameter is zero, 0 can not be a divisor, so it will crash, the following use exception handling this problem:

 #include  <iostream> #include   <string>using  namespace std;int div (int a, int b) {    if (b == 0 )     {throw string ("Parameter error."); /exception throw     }    return a/b;} Int main () {    try    {    div (1, 0);// Exception     }    catch found, with exception thrown (const string& s)      {    cout<<s<<endl;//Catch Exception     }     system ("pause");     return 0;} 

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/7E/93/wKioL1cE0v2AFLK9AAAYDl0MYEU208.png "title=" LPE "( 0hbb~c5]v@_0@22[$L. png "alt=" Wkiol1ce0v2aflk9aaaydl0myeu208.png "/>

The program can run normally, and you can see where the exception appears, so that you can clearly solve the problem.

Let's look at an example below:

#include <iostream> #include <string>using namespace std;void Test () {int* p = new int (1);    if (1) {Throw string ("error."); } delete p;}    int main () {try {test ();    } catch (const string& S) {cout<<s<<endl;    } system ("Pause"); return 0;}

The results show:

650) this.width=650; "src=" http://s2.51cto.com/wyfs02/M00/7E/97/wKiom1cE3OLBPiwnAAATZfNHtRk356.png "title="%] YI8CTC4U67W{1%H4HH (6p.png "alt=" Wkiom1ce3olbpiwnaaatzfnhtrk356.png "/>

This program run seemingly no problem, in fact, the problem is big.

void Test () {int* p = new int (1); if (1) {Throw string ("error.");    /program execution here, go directly to catch () that block,//cause new out of memory is not released, causing memory leaks. } delete p;}

Memory leaks:

Will cause you to open up the piece of memory after it can not be used, so many leaks, your computer will haha, will be very card, very card.

Memory Leak Hazards:

from the user's point of view of using the program, the memory leak itself does not have any harm, as a general user, there is no sense of memory leaks. What is really harmful is the accumulation of memory leaks, which eventually consumes all the memory of the system. From this point of view, a one-time memory leak is harmless, because it does not accumulate, and the implicit memory leak is very harmful because it is more difficult to detect than the usual and sporadic memory leaks.

Of course, this is not to say memory leaks, the following can be handled with exceptions to the above problem:

#include <iostream> #include <string>using namespace std;void Test () {int* p = new int (1); try//found exception {if (1) { Throw string ("error."); /exception throws}}catch (...) Catch Exception {Delete p;//frees open space throw;//exception re-throws}delete p;} int main () {try//found the re-thrown exception {test ();} catch (const string& S)//catch exception {Cout<<s<<endl;} System ("pause"); return 0;}

The results show:

650) this.width=650; "src=" http://s2.51cto.com/wyfs02/M00/7E/97/wKiom1cE3OLBPiwnAAATZfNHtRk356.png "title="%] YI8CTC4U67W{1%H4HH (6p.png "alt=" Wkiom1ce3olbpiwnaaatzfnhtrk356.png "/>

This will not cause a memory leak and will clearly display the wrong information in the console.

exception re-throw : There may also be situations where a single catch clause cannot fully handle an exception during exception handling. In some repair

After a positive action, the catch clause may determine that the exception must be handled by a higher-level function in the function call chain so that the catch clause can pass the exception to another catch clause in the function call chain that is more superior in the rethrow, and the rethrow expression is in the form:

Throw

The rethrow expression re-throws the exception object Rethrow can only appear in the compound statement of the catch clause. The object being re-thrown is its original exception object.


Stack expansion:

exits the compound statement and function definition as an exception when looking for a catch clause to handle the thrown exception

when an exception is thrown, the execution of the current function is paused and the corresponding matching catch statement is started. First check whether the throw itself is inside the catch block, and if so, find the matching catch statement. If there is a match, it is processed. Does not exit the current function stack and continues to look in the stack of the calling function . Repeat the above process repeatedly. If you reach the stack of the main function, there is still no matching, then the final program.

The process of finding matching catch statements along the call chain is called stack unwinding. When a matching catch statement is found and processed, it continues to follow the catch statement.


Matching rules for exception captures:

The type of the exception object must exactly match the type of the catch descriptor.

There are only a few exceptions to this scenario:

1. Allow conversions from non-const objects to Const.

2. Allow conversions from a derived type to a base class type.

3. Convert the array to a pointer to an array type, and convert the function to a pointer to the function type.

Exception Handling Summary:

Exception handling is through the Throw,try,catch, these three keywords, to find exceptions, and throw exceptions, catch exceptions, you can make corresponding processing. (This is just a simple exception handling)

C++primer_ Notes _ 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.