Master C ++ Builder's Included Art - First

zhaozj2021-02-08  220

Mastering the Art of debugging in C BuilderArticle 1 - Coding IT Right

Master C Builder's Included Art

First article - correct writing code

1 Introduction

2. Write clean code

3. Use abnormalities and abnormal processing capabilities

4. Use the record (logging) mechanism

5. Combined with the use of recording mechanisms and class abnormal processing mechanisms

6. Handle the exception generated outside your code

7. Your turn

8. Copyright description

Introduction This article, I will talk from the most basic beginning. But I hope that you can involve a wider level, not just for your program, debug. You will see that I think the meaning of debugging this word is not just through the Ide's built-in mechanism. I hope that when this small article, almost every reader can learn at least a new thing and hide it into your weapon. Remember, the less error (bug) in your program, the better your end user's feelings for your program; your processing of the error (bug) is better, the users find the error (BUG) Tell you so that you correct the error. Ok, now you have a seat belt, wear goggles, let us start a crazy approach!

Writing clean code

First of all, and maybe it is the most important point to write a clean, readable code is extremely important. Ability to review and add a comment after writing a piece of code, this code is used to do so, will save the countless painful hours of tracking the code in the future. Maybe you will spend more time to write, but when you spend N hours to track those difficult bugs, you will agree how to make the program code can be read. (You can easily complete the error). If you don't have this, I suggest you stop, read another SCOTT's wonderful article - the style of the code (if you need it, you will translate as soon as possible).

Using exceptions and exception handling power now goes to the next step, this is still a code based on the code. (In addition to in a very small number of cases, you can't always use the system built-in demistlers, so I know that other ways to find out these troublesome is always a good idea). This step is complete about how to do, more importantly, processing the system throwing you (generated) error when your form is abnormal. In the old days of recognition before the C standard, the application will usually issue an error signal by return value (this method is still in the OLE and some WinAPI functions). Obviously, you can easily ignore these (in fact, I do, I mean, do you often check the return value of a WinAPI function?).

So they decided ..., okay, we need a new mechanism, one you can't ignore. But you can handle, customize (custom Customize). The exception appeared. Want a special error type flag? Easy to define a new exception type (just a class, nothing else), throw out (producing this exception). Finished.

example:

Class myException

{

PUBLIC:

Ansistring iMessage;

MyException (ANSISSTRING Message) {iMessage = Message;

}

Throw New MyException ("Test Exception Message");

It's that simple! (Of course not very complete, I will pack it very quickly). Beautiful and simple, and very easy to customize to meet your needs. Okey, you will ask: "I can produce an abnormality, but how to handle them? I mean, I want to rule out the exception from my code in the first time!" Of course it is easy to do, actually It's easy to customize! The Standard Commission defines the Try {/ * code * /} catch (...) {/ * code * /} mechanism, like an exception mechanism, it is fully customized to meet your needs! Just put your execution code segment in the TRY module, you also need a catch () or __finally module to tell (if) get an exception. Now is the benefits you do, you define a class class class and enter variables to capture exceptions - by declaring catch (). (In the previous example, it should be such -catch (myException & e) {/ * to write capture to abnormal processing code here * /}) In order to make this system more powerful, you can build a complete subclass inheritance tree. This way you can capture all exception types from this base class when you capture the base class (a good example in the VCL is that all exceptions are inherited from the Exception class, so Catch (Exception & E) will capture all The VCL is abnormally, of course, the package also includes what you are produced. But except EsocketError, see Xiphias in http://www.bytamin-c.com/'s HOWTO (if you don't like E text, I will translate as soon as possible). With this idea, I will explain the other steps later). To make it more powerful, the Standards Committee decided to include the following statement Catch (...), there is three points in parentheses. This statement allows us to capture any exceptions, I mean all the exceptions. Also want some strength? Of course, you can declare the additional catch (), which is similar to if..else if ... It is necessary to keep in mind here! If you capture an exception type, then it will not be captured again! So look at the code below ... TRY

{

// Normal operation code for the program

}

Catch (EdbengineError & E)

{

// Process the error based on the database engine

}

Catch (Eexternalerror & E)

{

/ / Usually handle Windows-based errors

}

Catch (Exception & E)

{

/ / Handle all other VCL errors

}

You can see, "Is EDBENGINEERROR? Yes -> Process, isn't it? -> Continue to capture" "Is EEXTERNALROR? Yes -> Processing, not? -> Continue next capture", etc. ... This order is arranged .

Then there are more content. If you want to do something for an exception, you don't want an exception to disappear, you can reap out (produce) this exception. It will continue to find a new catch () process to handle it. I can't say that I often do this. But it is best to know that it is as simple as "throw". That's it, Throw will take another catch to handle another catch after the exception has been processed.

Finally, not the least least, this part is not included in the standard specification, it is more like a Borland proprietary increased version) is __finally declaration, use a __finally {} module, you can specify whether no exception Will run the code. Here is the most convenient place to clear the local variable allocated by the New method and reset all the flags that should be set back to the normal state (for example, reset a wait state of the mouse pointer to normal state).呸, too much! Take a break, you can take a look at the Exception class in C Builder Help, (All E started, you will notice that they are inherited from the Exception class. This is also customized to customize your own exception class. Exercise!) When you come back, we will go to the next step.

Use record (logging) mechanism

You can't always use the defective device to be insect, sometimes you can't rely on the power of the built-in errorer, so sometimes you will have to help other degne means to debug the program. (Typical examples such as NT service, ISAPI / CGI program, real-time applications ... etc.) At this point you will have to help our experienced programmers will talk about the old-fashion / debugging technology. For example, what happened to see what the program's headscarf happened to see if a logging mechanism is used. Fortunately, there are many ready-made mechanisms to make our work easier. Here I will talk about the three ways I prefer, you can also give me your own method Email, I will consider joining this section.

Okay first says the first, (debug / degne output string) OutputDebugstring. Fortunately, Microsoft has achieved a very broad debug / division of the wrong subsystem for us. Includes mechanisms to implement your own debug / defect recording system. When the program is running within a debug / in the wrong process, outputDebugstring outputs its parameters (a c string) to the output context of the debug / deactivator, if the debug / division is not running, OutputDebugString is ignored. If there is no pop-up message, OutputDebugstring can also run well on the terminal. If you distribute it to the customer, don't forget to remove it (through #ifdef debug ... # Endif '), the program can run faster. "Wow, it's good and easy!" You may say "but what should I do when the program cannot run within the debug / deactivation?"

Please keep in mind that this is just my point of view. Based on an idea, I personally use Geperts's DBugint.PAS interface to debug / debug. This is a very good independent applet. If you prefer, you can distribute it to your customers. If you don't do this, like OutputDebugstring, if you don't have installed, it doesn't do anything:) (it will pay attention to whether the terminal is already installed on the machine). To use dbugint.pas, it is easy to add it to your project and add #include "dbugintf.hpp" (because it is a PASCAL file, you must join your project to generate an HPP header file. .) Then you just need senddebug ("To send a string" in the record "); or you may want to be more flexible, and sendDebugex-add a message type parameter to call TMSGDLGTYPE (detailed reference VCL online help), SendMethodenter, SendMethodeXit, And SendSeparator, etc. (very self-explanatory name). Just don't forget to join the necessary package package, if you intend to give this terminal (gdebug.exe) to some of the end users. Gexpert can be obtained from http://www.gexperts.org/ and is free. The third kind I want to point out is that this may be the most difficult choice - implement your own record console. Can not be as simple as you think! You may first think of "Throw a Richedit control on the form, set it to read-only, then start logging, right?" Wrong! Theory is very good, but practice, use the Richedit control to record the running speed of the program will reduce the running speed of the program, break the memory, lost, usually make the entire machine slow down within 10 minutes! ! (To tell why you have to spend some time, but I can guarantee you). So what you need is to plan your recording mechanism, and start planning a custom control if you want a colored icon. There is also a choice, you need to do something, but it is very effective. That is to use a listbox control to record and set the style property to lbownerdrawfixed, so the handle will be painful. (This is also made of gexperts and its GDebug Console). To do a lot of work, but haha, if you want to do it ...

Combined with the recording mechanism and the exception handling mechanism now go to the next step:) (bet you have never realized setting up an excellent debug / defect system need to do so much work!) You don't always expect various accidents What will happen, and most of the time is a large number of demonstration tests (try to attack programs, trying to crash), you don't have to worry about it. Below, this technology I suggest that any component developers should first test a new component / new code in the IDE. Because an exception in IDE will bring a lot of problems, sometimes even restart IDEs are not helpful (I have done this yourself). In fact, it is also very simple. Before each function of your code, or at least before and after all major functions:

Try

{

Front-end code

}

Catch (Exception & E)

{

SenddebugMessage ("Exception Caught In ClassName :: functionname of type:" E.CLASSNAME ()

"With the message:" E.MESSAGE);

(And use functions of the class name and function name instead of ClassName and FunctionName in the string). This way, you quickly know where the abnormality happened, and you don't have to force the IDE.

Okay, it's time to review it. How is the classname () method help us? I don't want to get a "exception" string every time. Is it because I declare the e-declaration as an exception? wrong. This is a Cool part of the VCL. Any class from TOBJECT inherits automatically knows its own type, the type of its base class, and many interesting information, you can check the help of Tobject. So even if we use Exception & E, E.ClassName () will find the actual class name of our exception (translator Note: C polymorphism). The cost of these benefits is the volume of executable files, almost all C Builder / Delphi programmers will find this. (No pain, no gain) did not suffer, there was no harvest. They said ....

Xiphias adds the TStringList's AddingLine method, and the SaveTofile method is another record (logging) effective form. Finally, your app should always write a log file (logfile), or then rewrite the record file each time you capture an exception.

The exception generated by handling your code is now the last code-based step before we start learning the IDE-based decentralizer. But maybe when there is a serious error, this is the most important step for decorative applications. For example, this is an ideal time to display a dialog box containing an error detail. At this time, the pop-ups on the screen can be convenient for end users to report errors to you. I dare to guarantee you hate "OH, what is the report on what address has occurred in what address. In fact, it is very easy to implement better, nor does it limit how you intend to handle it. The first step is to create a function like this like this in your main form (for example, the first form of the engineering automatic creation form list:

Void __fastcall applevelexceptionhandler (TOBJECT * Sender, Exception * e)

{

}

Then add the appropriate code to display the error (E-> Message), error type (remember E.ClassName (), only it is its E.CLASSNAME ()), and contact your detailed approach and other you want Plus anything. The second step is of course hook it with the system, which is easy to achieve in C Builder:

Application-> Onexception = ApplevelexceptionHandler;

Add the previous line of code to the oncreate event of the Form. Don't be embarrassed! Over you added this line, you can almost guarantee that you will not miss any exception, and it will appear in front of you when you fail!

Your turn now you have got all your useful information you just learned. It's time to start adding them to your current project, otherwise I will forget it. Otherwise, turn it into part of the program habits. This is your freedom!

In this series of next part, I will discuss the use of internal construction modulators, let's take a look at what your program is running, how to track code, set breakpoints, check the variable, and will put a novice Think of all other interesting tools that are scared. Until here, your BUGS may just be a small bug.

Original: Bill King

Translation: Hop Pacific - CKER

Copyright Description: Domestic website, there are many contents of C Builder, but more software, components are mainly. Most of the forum can not be satisfactory, very empty. The book is expensive, but the content is too expensive. For beginners who are insufficient, self-study is not enough, so they want to do our best.

All materials in the article come from foreign websites. Because E text is inconvenient, turn into Chinese. Because English and computers are not very good, the mistakes in the text are inevitable. If you feel useful, I plan to continue to collect some useful things.

If you have any comments and suggestions, please allow mailto: cker@sina.com

You can copy, distribute, download this document free. However, you may not take it, change this article, or use this article to see any form of interest.

Pacific

2001.2.4

转载请注明原文地址:https://www.9cbs.com/read-2192.html

New Post(0)