Understanding first chance and second chance avoiding single-step debugging

Source: Internet
Author: User

original link Address: http://blog.csdn.net/Donjuan/article/details/3859160

In the now C + +, Java,. NET code, many code errors (bugs) are expressed in the form of exceptions. Because of the time limit or a variety of reasons, many programmers in the process encountered an unhandled exception of the first reaction is the try ... catch (Exception e) {...}. However, when the code is developed to a later stage, this simple and rough way to solve the code error (bug) is shown in other irrelevant places, sometimes causing the program to be randomly unstable and difficult to debug. For example, execute the following code and you will find that the output value is 12345.6789:

usingSystem; Public classclass1{ Public Static voidMain () {Console.WriteLine (Calculate ("12345.6789 + 987654321l")); }    Private Static DoubleCalculate (stringexpression) {        string[] numbers = expression. Split ('+'); returnRedundantparsefordemoonly (numbers[0]. Trim ()) +redundantparsefordemoonly (numbers[1].    Trim ()); }    Private Static DoubleRedundantparsefordemoonly (stringNumber ) {        Try        {            return Double.        Parse (number); }        Catch        {            return 0; }    }}

Of course, you can say that just forcing all programmers in the project to not catch the generic exception is OK, but the tiger always has a nap, and most of the project team because the talent echelon construction problems will have a few new people ...

I found in my work that many programmers do not understand, or do not pay attention to the output in table 2, wasting a lot of good debugging opportunities. So I see a lot of good programmers are very hard to step through debugging, step-by-year tracking code. This process is not only hard, but also very error-prone, because the single-step tracking code makes it easy for a person to faint. You can actually take advantage of the structured exception handling (SEH) provided by Windows to help you quickly find the problem.

When the program is running, especially if there is an exception in the program, if you use the command-line debugger such as Windbg.exe, CDB.exe, or if you are mindful of the output of the text in Visual Studio Output window, You will see output similar to the following:

0x004116a9 inch 0xC0000005 0x00000000 ..... First0x7c812aebinchar0x0012fd88.
Introduction to Exception mechanisms

When the CPU runs to some illegal instructions, such as a 0 error, access memory page failure and other instructions, the CPU generates a hardware exception, different exceptions have a fixed exception code as identifiers, the exception is generated after the CPU temporarily cannot continue to execute subsequent instructions-because the subsequent instructions may also be invalid. Of course, the whole computer system can not be so, so the CPU built an exception processing table-this exception processing table only run in kernel mode code to access, the operating system at the start of the initialization of the exception processing table, for each exception to register an exception handler, so this table looks like:

After the CPU generates an exception, the exception handler is searched for the corresponding exception handler in the exception-handling table, and the exception handler is called to perform the appropriate processing before proceeding with other code.

In addition to handling CPU-customized hardware exceptions, there are some empty table entries in the Exception handling table so that the operating system can implement software exceptions by adding custom exception codes and corresponding exception handlers. In the Windows operating system, programs can trigger software exceptions by calling Win32 's RaiseException function. As a result, exceptions in C + + and. NET are actually implemented by calling RaiseException, but the exception handling table is not large and only holds no more than 256 exception handler information, so Windows defines only a few common exception codes to represent C + + and. NET exceptions.

For CPUs, hardware exceptions, software exceptions, C + + exceptions, and. NET exceptions are triggered and processed in the same way, which is called Structured exception handling (SEH) in Windows.

Exception handling

1. When there is an exception in the program after the occurrence;

2. Seh begins by backtracking the stack contents, looking for an exception handling block within the program (the catch block that we usually know), and if an exception handler is found to handle the exception, Windows releases the stack underneath the function where the exception handler block is located, and execute the code inside the exception handling block.

3. If Windows does not find any exception processing block to handle this exception, that is, to the program entrance (main) function does not find a suitable exception processing block, Windows will use its own exception processing block to handle the exception;

4. Windows comes with an exception block that checks to see if your program has a debugger attached, and if so, Windows interrupts the program and gives control to the debugger.

5. If no debugger is attached to your program, Windows starts registering the default autopsy debugger in the registry, in general, the default debugger for Windows is Dr Watson, and this debugger's job is to pop up the famous "Debug or Terminate" dialog box (or " Do you want to send error reports to Microsoft? dialog box):

In the above process step, the first step through raiseexception to trigger the exception, Windows will first check whether your program is being debugged, if there is a debugging is attached to your program, Windows to debug send a debug message, Notifies the debugger that an exception occurred, asking the debugger to interrupt the program, and by default the debugger ignores the message-because our pure debugger always believes that programmers can write good code. This step is referred to as the first opportunity in the debug terminology-first chance-to observe the environment that triggered the exception at the scene where the exception occurred.

The 3rd step after the operating system to handle this exception, in the debug term called the Second Chance (Second chance), because this time the program is actually dead (there will be no life activities)-not critically ill, So this time, even if you attach the debugger to check the environment that triggered the anomaly, just as the coroner was examining the cause of the abnormal death of the person-postmortem commissioning.

Set debugger do not ignore first chance exception

In the process of development, we certainly want to check the code error (bug) when the program is critically ill (first chance exception), so if there are some inexplicable bugs in the program, when debugging the program, it is best to tell the debugger not to ignore the first chance exception. Because if the exception is caught in the code inside the program, it is likely to cause us to ignore important clues.

In WinDbg, use the following command to tell the debugger not to ignore the first chance exception:

Sxe Exception Code

Note there is a space behind sxe, for example, in debugging. NET program, you can use the command sxe 0xe0434f4d to make the debugger break the execution of the program before the catch block executes.

You can use the command

Sxd Exception Code

To enable the ability to ignore first chance exceptions.

In Visual Studio, refer to one of my other articles to learn how to set up: CLR Debugger-Interrupt program execution when a program throws an exception

How do I know if the debugger is ignoring the first chance exception?

By looking at the output information inside the debugger, you can see if the debugger has enabled the ability to interrupt program execution when the first chance exception is triggered.

Inside Visual Studio, you can view the output of the text in the Output window:

This output indicates that the debugger ignores the first chance Exception

Inside the WinDbg, an output similar to the following indicates that the debugger ignores the first chance exception:

Appendix

You can use the following code to try out the concepts explained above:

//exception handling. Cpp:defines The entry point for the console application.//#include"stdafx.h"#include<iostream>#include<windows.h>#include<excpt.h>using namespacestd;intExceptionfilter (unsignedintCodestruct_exception_pointers *EP) {    if(Code = =exception_access_violation)returnException_execute_handler; Else        returnException_continue_search;}voidcpptestfunction () {Try    {        Throw "Test Cpp Exception"; }    Catch(Char*) {cout<<"char * Exception caught"<<Endl; }}int_tmain (intARGC, _tchar*argv[]) {    int*p =NULL; __try {*p =1; } __except (Exceptionfilter (GetExceptionCode (), GetExceptionInformation ())) {cout<<"ACCESS violation caught"<<Endl;    } cpptestfunction (); return 0;}

Understanding first chance and second chance avoiding single-step debugging

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.