Windows core Programming Study Notes-Chapter 23

Source: Internet
Author: User
Tags exit in

Chapter 4 terminate a processing program

I. Benefits of She (structured exception handling)

Ii. What is she

Iii. How to Use she

Iv. How she works

I. first understand the benefits of She: we can concentrate on the normal workflow of the software when writing code. If any problem occurs during running, the system will capture the problem and notify us. Using she does not mean that errors in the code can be completely ignored, but you can separate the software attention feature writing and software exception handling tasks.

Ii. She has two features: Termination and exception handling. This chapter discusses termination and exception handling. Differentiate between she and C ++ Exception Handling: the form of C ++ exception handling is represented by the use of the keyword catch and throw. This structured exception Processing Form is different. Microsoft
Visual c ++ supports exception handling. The internal implementation of Visual C ++ actually utilizes the structured exception handling functions of compilers and Windows operating systems.

3. Terminate the processing program so that no matter how a code block (gaurded body) exits, the other code block (Termination handler) can always be called and executed. The syntax for terminating the processing is as follows (when Microsoft Visual C ++ compiler is used ):

_ Try

{// Gaurded body}

_ Finally

{// Termination handler} // The _ finally code block can be executed unless exitprocess, exitthread, terminateprocess, and terminatedthread are called to terminate the process or thread.

Example:

1. funcenstein2 function:

DWORD Funcensterin2(){DWORD dwTemp;//1.do any processing here_try{//2.request permission to access protected data, and then use it.WaitForSingleObject(g_hSem, INFINITE);g_dwProcetedData = 5;dwTemp = g_dwProcetedData;//return the new value;return(dwTemp);}_finally{//3.allow others to use protected data.ReleaseSemphore(g_hSem, 1, NULL);}//continue processing--this code will never execute in this version.dwTemp = 9;return(dwTemp);}

Terminate the processing program to prevent premature execution of the Return Statement. When a return statement exists in a try block and tries to exit the try block, the compiler will execute the finally code block before it. This function ensures that the semaphore is released before the function exits.

Principle: When the compiler checks program code and finds a return statement in the try block, it will generate some code to save the return value in the temporary variable it created, and then execute the Finally block, this process is called local expansion. That is, when the system executes the finally code block because the code in the try code block is extracted and exited, partial expansion occurs.

Disadvantage: for this mechanism to run, the compiler must generate some additional code, and the system must also execute some additional work. All statements that require early exit in the try block should be avoided, such as return, continue, break, and Goto.

2. funcfurter1 function:

DWORD Funcfurter1(){DWORD dwTemp;//1.do any processing here._try{//2.request permission to access protected data, and then use it.WaitForSingleObject(g_hSem, INFINITE);dwTemp = Funcinator(g_dwProtectedData);}_finally{//3.allow others to use protected data.ReleaseSemaphore(g_hSem, 1, NULL);}//4.continue processing.return(dwTemp);}

If the funcinator function in the code block has a defect, the program accesses the invalid memory. If no she exists, this eventually leads to a Windows Error Reporting (wer ). In this way, the process will be terminated (because of illegal memory access), but the semaphore will still be occupied and will no longer be released. Threads in other processes will not get the CPU time slice because of endless waiting for this semaphore. If the statement for releasing semaphores is placed in the Finally block, the semaphores can still be released even if the memory access violation occurs in the function called in the try block.

However, from Windows Vista, the try/finally framework must be displayed to ensure that the finally code block is executed when an exception occurs. In the early Windows system, when an exception occurs, the Finally block cannot be absolutely executed. For example, in XP, if a "Stack depletion exception" occurs in the try code block, the Finally block may not be able to be executed.

Calling exitthread or exitprocess can terminate the thread or process immediately without triggering finally code block execution. Similarly, if the current thread or process has to end because another program calls terminatethread or terminateprocess, the finally code block will not be executed. Some C-runtime functions (such as abort) cannot execute finally blocks because they call exitprocess internally.

3. funcarama3 functions:

DWORD Funcarama3(){//IMPORTANT:initialize all variables to assume failure.HANDLE hFile = INVALID_HANDLE_VALUE;PVOID pvBuf = NULL;_try{DWORD dwNumBytesRead;BOOL bOk;hFile = CreateFile(_T("SOMEDATA.DATA"), GENERIC_READ,FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);if (INVALID_HANDLE_VALUE == hFile){return false;}pvBuf = VirtualAlloc(NULL, 1024, MEM_COMMIT, PAGE_EADWRITE);if(NULL == pvBuf){return false;}bOk = ReadFile(hFile, pvBuf, 1024, &dwNumBytesRead, NULL);if (!bOk || (dwNumBytesRead != 1024)){return false;}//do some calculation on the data.}_finally{//clean up all the resources.if (pvBuf != NULL)ViutualFree(pvBuf, MEM_RELEASE | MEM_DECOMMIT);if (hFile != INVALID_HANDLE_VALUE)CloseHandle(hFile);}//continue processingreturn true;}

The essence is that all cleanup tasks are put in one place: Finally blocks. Otherwise, these cleanup tasks must be processed in each judgment error.

4. Final funcarama4:

DWORD funcarama4 () {// important: Initialize all variables to assume failure. handle hfile = invalid_handle_value; pvoid pvbuf = NULL; // note that the function cannot be successfully executed bool bfunctionok = false; _ Try {DWORD dwnumbytesread; bool Bok; hfile = createfile (_ T ("somedata. data "), generic_read, file_cmd_read, null, open_existing, 0, null); If (partition = hfile) {_ leave;} pvbuf = virtualalloc (null, 1024, mem_commit, page_eadwrit E); If (null = pvbuf) {_ leave;} Bok = readfile (hfile, pvbuf, 1024, & dwnumbytesread, null); If (! Bok | (dwnumbytesread! = 1024) {_ leave;} // do some calculation on the data. // indicates that the entire function is successfully executed. bfunctionok = true;} _ finally {// clean up all the resources. if (pvbuf! = NULL) viutualfree (pvbuf, mem_release | mem_decommit); If (hfile! = Invalid_handle_value) closehandle (hfile);} // continue processingreturn bfunctionok ;}

Keyword _ leave will cause the code execution block to jump to the end of the try block (that is, closing curly braces ). In this case, code execution will normally go from try to finally, so no additional overhead will be incurred.

When terminating the handler in a function, it is best to initialize all resource handles as invalid values before entering the try block. In this way, you can check which resources are successfully allocated in the Finally block to know which resources need to be released. Another common way to check which resources need to be released is to set the flag for successfully allocated resources, and then check the flag in the Finally block to determine whether the resources need to be released.

4. The above example is similar. add two points: 1. Cause the Finally block execution.

1) normal code control flow from try block to finally.

2) partial expansion: The program control flow is forcibly transferred to the Finally block from the early exit (Return, break, continue, got, longjump, etc.) of the try block.

3) expand globally.

2. benefits of using a terminated program:

The cleanup work is concentrated in one place and can be executed to simplify error handling.

Provide code readability.

Make the code easier to maintain.

Ø if used correctly, the impact on program performance and volume will be minimal.

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.