Memo: Exception Handling in VC + +

Source: Internet
Author: User
Tags terminates throw exception try catch

When a program encounters an exception or a serious error, it usually means that it cannot continue to function properly and needs to stop executing. Any design is inseparable from the handling of anomalies and errors. If the designer does not actively evade the program exception, often in the event of an exception, will be terminated by the system and directly exit. This is very unfriendly to the user.

If you actively handle an exception, you can explicitly prompt for an error to occur, or you can prevent the program from terminating abnormally. A better deal is to anticipate some errors at design time, allowing the user to circumvent these errors in order for the program to run smoothly. For some unpredictable anomalies , we also need to pass the VC + + exception handling mechanism, explicitly tell the error has occurred, and ensure that the program continues.

VC + + provides two different types of exception handling:
Structured exception SEH (Structured Exception handling,) and typed C + + exceptions.
Seh is unique to VC + + compilers, so if you want to write portable code, you should not use SEH. He can only make a difference in the Windows system. If you only want to write a Windows app. Then, it is best to choose Seh to handle the exception. SEH is more convenient and flexible than a typed C + + exception.

Structured exception SEH

__try,__except,__finally is the processing model for SEH that is available on the Windows series operating system platform.

__try,__except: Indicates that an exception occurred in the try {} statement and will go to the except () {} module execution. If try{} is not an exception. The except module has been skipped. Continue execution of code after except {}.

__try, __finally : Indicates that a try {} statement, whether or not an exception occurred, finally{} module will be executed. __try __finally Not much usage, no detailed explanation. Just use the right place.

    _ __leave: generally used in try{}. Represents exiting the try module and does not execute the statement after leave. The return of the root as in the function. However, this only exits try{}.

__try,__except Simple usage Demonstration :

int_tmain (intARGC, _tchar*argv[]) {    intv1, v2; V1=1; V2 =0; Doublex=0; __try {//if (v2==0) ___leave; //add ___leave to this sentence. The code after leave does not execute the code after executing try except out of the try. x = v1/v2;//x = MyFunc (v1, v2);cout << x <<Endl; } __except (1)//try to change to 0 or-1 to see the effect{cout<<"error!"<<Endl; } System ("Pause"); return 0;}

In parentheses after the __except, it is an expression or a numeric value. The expression returned should also be a numeric value. This value of 1-3 indicates that there are three kinds of except in the process:

    • __except (-1) terminates abnormally and exits the program. Seldom use this. Unless the person wants to terminate their own program.

    • __except (0) jumps out of the current exception and continues to be handled by the next exception except.

    • __except (1) accepts an exception. Executes the statement in the exception {}. The above two values-1, 0 will not execute the statements in the except{...}.

Of these three values, in Windows, there are three constants that represent:

Exception_continue_execution (–1)
Exception_continue_search (0)
Exception_execute_handler (1)

We can also use a function to return three values. Allow except to be handled more precisely when triggered. This function typically calls the API functions handled by Windows two error codes:
GetExceptionCode (): Returns the error code;
GetExceptionInformation (): Gets the error message structure.

Examples of embedding exception handling and custom handler functions:

intErrorfunc (unsignedintCodestruct_exception_pointers *EP) {Puts ("my Error infomathion."); if(Code = =exception_access_violation) {Puts ("caught AV as expected."); returnException_execute_handler;//= 1 Execution of the called except process    }    Else{puts ("didn ' t catch AV, unexpected."); returnException_continue_search;//=0 continue to let the next except handle    };}DoubleMyFunc (intAintb) {DoubleR; //exit (0);__try {R= A/b; cout<<"cacle ..."<<Endl; } __except (Errorfunc (GetExceptionCode (), GetExceptionInformation ())) {//if Errorfunc returns a value of 1, the following statement executesUnsignedintCode =GetExceptionCode (); cout<<"error!:"<< Code <<Endl; //throw;} cout<<"... .. end1 ..."<<Endl; returnR;}int_tmain (intARGC, _tchar*argv[]) {    intv1, v2; V1=1; V2 =0; Doublex=0; __try {x= MyFunc (v1, v2);//call function, embedded __try __except demonstration. cout << x <<Endl; } __except (1) {cout<<"error!"<<Endl; } cout<<"... .. end2 ..."<<Endl; System ("Pause"); return 0;}

In the SEH exception handling model, exceptions are thrown by the raiseexception () function. The RaiseException () function acts like a throw in the C + + exception model. This function can be used to proactively handle predictable anomalies.

An example of a proactive throw exception:

int_tmain (intARGC, _tchar*argv[]) {    intv1, v2; V1=1; V2 =0; Doublex=0; __try {//x = v1/v2;RaiseException ( -,0,0, NULL);//actively throwing error 100 is the exception code that you definecout << x <<Endl; } __except (1) {UINT code=GetExceptionCode (); if(code== -)//Judging yourself from the exception code throwncout <<"error! Code:"<< Code <<Endl; } cout<<"... end ..."<<Endl; System ("Pause"); return 0;}

Typed C + + exceptions

C + + exception handling is simple, is three keyword try, throw, catch to complete. He has a related role in many places. But here's just a simple idea.

Try{  //write some code here  intA=Ten, b=0; intx; if(b==0)     Throw 1;//throws an exception. Terminates the following code execution.   if(a==1); Throw 2;//throw an exception again. Terminates the following code execution. x= A/b;//b=0. An operation exception is generated. }Catch inti{if(i==1)//the value thrown by the throw =1cout <<"b=0 is error!"<<Endl; if(i==2)//the value thrown by the throw =2cout <<"I=1 is error!"<<Endl;}Catch(...) {}//Accept All Exceptions 

If you want to use try{} catch{} to catch some unexpected anomalies, it is unreliable. That is, he needs to find the exception in the try {} and then throw the exception and let the catch handle it. If you can't find an exception, if you can't throw it out, you can't handle it. As in the example above: if (b==0) throw 1; Don't say that. execution to x=a/b; is to produce a system error. This exception is not actively recognized in try{}catch{}. But there are many uses for try and catch. Can find more information to understand the next. I have not understood clearly.

The following content is not easy to understand:

When a catch does not catch a matching exception, the default termination function is called. You can call Set_terminate () to set the terminating function, which is a function pointer with the type: void (*terminate) (); The default unexpected () function is actually called, and the default unexpected () invokes the terminating function set in Set_terminate (). You can use set_unexpected () to set the unexpected.

as follows: (but this piece of code compiled under VC does not happen!) )

voidmyunexpected () {Cerr<<"unexpected called\n"; Throw 0;//throws int (in exception-specification)}voidMyFunction ()Throw(int) {    Throw 'x';//throws char (not in exception-specification)}int_tmain (intARGC, _tchar*argv[]) {    intv1, v2; V1=1; V2 =0; Doublex=0;    set_unexpected (myunexpected); Try{myfunction (); //x = v1/v2;    }    Catch(int) {Cerr<<"caught int/n"; }    Catch (...) {Cerr<<"caught other exception (Non-compliant compiler?) \ n"; };}

VC in Release mode if the compiler code optimization option is selected, the code in the try block is searched, if the throw code is not found, the try catch structure is considered superfluous and optimized. This is caused in release mode. Throws an exception if the active throw is not in try{}. In the VC Release compilation mode, the try catch is ignored.

Memo: Exception Handling in VC + +

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.