C Language exception Handling (52)

Source: Internet
Author: User

Let's take a look at exception handling today, before we look at exception handling in C + +, let's see the exception handling in the language. So what is an anomaly? An exception may occur during program operation,the exception (Exception) differs from a bug in that the exception is an execution branch that is expected to run when the program runs, and that the bug is an error in the program and is not expected to run.

Let's take a look at the exception and Bug comparison:a> exceptions such as runtime generated in addition to 0 of the situation, need to open the external file does not exist, the array accesses the;b> Bug is the use of wild pointers, the heap array is not released after the end of use, select Sort cannot handle an array of length 0 . The classic way of handling in C is:if ... else .... The normal code logic is handled in the IF statement, and the exception case code is handled in the Else statement.

Let's take the code as an example to see the handling of the division operation exception

#include  <iostream> #include  <string>using namespace std;double divide ( DOUBLE&NBSP;A,&NBSP;DOUBLE&NBSP;B) {    const double delta =  0.000000000000001;    double ret = 0;         if ( ! ( (-delta < b)  &&  (b < delta)  )     {         ret = a / b;    }     else    {        ret =  0;    }        return ret;} Int main () {    cout << divide (1, 1)  << endl;     cout << divide (1, 0)  << endl;     return 0;}

Let's look at the compilation results

The result of the execution is correct, but what if we print a result of 0/1? We don't know if it's the right thing to do or the situation that is abnormal. Then we add a parameter to the divide function in the above program to indicate whether the execution result is correct or not, according to the value of this parameter to determine if the execution is normal. The procedure is as follows

#include  <iostream> #include  <string>using namespace std;double divide ( Double a, double b, int* valid) {    const double delta  = 0.000000000000001;    double ret = 0;         if ( ! ( (-delta < b)  &&  (b < delta)  )     {         ret = a / b;                 *valid = 1;    }     else    {        *valid  = 0;    }        return ret;} Int main () {&NBSP;&NBSP;&NBSP;&NBSP;INT&NBSP;VALID&NBSP;=&NBSP;0;&NBSP;&NBSP;&NBSP;&NBSP;DOUBLE&NBSp;r = divide (1, 0, &valid);         if (  valid )     {        cout <<  " r =  " << r << endl;    }     else    {        cout <<  "Divided  by zero ... " << endl;    }    return 0;

Let's take a look at the compilation results

Let's try 0/1 again.

We see that the results have been executed correctly. However, this program has a flaw, that is, the divide function requires 3 parameters, it is difficult to understand its usage, and the Divide function call must determine the result of valid, when the valid is true, the result of the operation is normal; When valid is false, the result of the operation is abnormal 。 In the C language there is also a way of exception handling, judged by setjmp () and longjmp () . Let's talk about the prototypes of these two functions and their meanings:a> int setjmp (jmp_buf env) is to save the current context in the jmp_buf struct;b> void longjmp (jmp_buf env, int val) from J The MP_BUF structure restores the setjmp () saved context, which is eventually returned from the SETJMP function call point, and the return value is Val; let's do the analysis with the sample code.

#include  <iostream> #include  <string> #include  <csetjmp>using namespace  std;static jmp_buf env;double divide (double a, double b) {     const double delta = 0.000000000000001;    double ret  = 0;        if ( ! ( (-delta < b)  &&  (b < delta)  )     {         ret = a / b;    }  &NBSP;&NBSP;&NBSP;ELSE&NBSP;&NBSP;&NBSP;&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LONGJMP (ENV,  1);     }        return ret;} Int main () {    if ( setjmp (env)  == 0 )     {         double r = diVide (1, 0);                 cout <<  "r = "  << r << endl;     }    else    {         cout <<  "Divided by zero ..."  << endl;    }     return 0;}

After it enters the IF statement of the main function, it saves 0 in the current env, and the SETJMP function saves the current context information. Then execute the Divide function, enter into the divide function, and go to the Else branch. longjmp function will save 1 to Env and the execution of the program to jump to setjmp, when Env is 1, so the condition is not set, so will print out divided by zero ..., let's look at the results of the compilation

Let's take a look at 1/1, go into the divide function, it will execute the IF statement after the normal calculation will return directly to RET, will output the result

Although this is a two parameter, it has a certain flaw. The introduction of setjmp () and longjmp () will inevitably involve the use of global variables, and violent jumps lead to lower readability of the code, which is essentially the IF ... else ... Exception handling methods. Its violent jumps break the structure of the C language (sequential execution, select execution, loop execution). The classic exception handling in C language causes the logic in the program to mix with a lot of code that handles the exception. The combination of normal logic code and exception handling code causes the code to expand rapidly and is difficult to maintain. In C + + There will definitely be a better way to handle exceptions, and we'll continue to learn later. Through the C language in the exception processing learning, summed up as follows:1, the program will inevitably occur anomalies; 2. Anomalies are runtime issues that can be foreseen in the development phase; 3, C through the classic if ... else ... Handles exceptions in a way that has better exception handling in C + +.


Welcome Everybody to learn C + + language together, can add me qq:243343083.

C Language exception Handling (52)

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.