1. Trang chủ
  2. » Công Nghệ Thông Tin

The book of visual basic 2005 net insight for classic vb developers 2006 - phần 6 pptx

51 254 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

bvb_02.book Page 238 Thursday, March 30, 2006 12:39 PM 8 BUG PROOFING Bugs—flaws in a program’s logic, design, or syntax—have crashed everything from personal computers to a $125 million Mars orbiter. This chapter examines how you can code defensively, restrict possible problems, and pro- tect yourself from bugs. You’ll also learn how to handle common problems by using Visual Basic 2005’s structured exception handling, which replaces the well-worn On Error Goto statement of classic VB. This error-handling infrastructure allows you to filter out specific errors, pass error information in exception objects, and deal with exceptions in deeply nested code. Traditional VB error handling used a sort of “traffic redirection” to deal with problems. That made it very difficult to isolate error-handling code from application code, and the resulting spaghetti-like tangle could actually make errors more likely. VB 2005 exception handling works like a handcrafted net. You design this net to catch specific error types, and then handle them appropriately if they occur. Of course, even the best error-handling methods won’t stop every potential problem. Eventually a bug will slip into your program, producing bvb_02.book Page 239 Thursday, March 30, 2006 12:39 PM 240 Chapter 8 an error that you can’t fix, or generating results that just don’t make sense. VB 2005 continues to offer the wide range of debugging tools found in earlier versions of Visual Basic, with some additional refinements. In this chapter, you’ll learn how to use these tools to track down and exterminate any bug that’s loose in your software. You’ll also learn some debugging techniques that will help you peer into the low-level gears and wires of your applications and uncover what’s really taking place while your code executes. New in .NET Visual Basic has always provided a rich set of debugging tools, and these tools are still available in VB 2005, with a few helpful tweaks and improvements. The real story, however, is the error-handling syntax that modernizes VB to match other .NET languages. Some of the changes you’ll see in this chapter include: Structured exception handling Finally, you can remove the last Goto statement from your application and clean out spaghetti code for good. Visual Basic 2005’s structured exception handling helps you ensure that your application’s error recovery logic is as clean and well organized as the rest of your code. Error highlighting Visual Basic has always been famous for catching errors as you type, and with the .NET platform, its intelligence has grown. Now troublesome code will be automatically underlined, identifying where you’ve tried to use a method or variable that doesn’t seem to exist, or where you’ve performed an illegal data conversion. VB 2005 even flags code that isn’t an error but might indicate an unintentional slip-up, like defining a variable but never using it. Type safety Accidental conversion errors are no longer a silent killer. VB 2005 allows you to forbid dangerous conversions, thus giving you tighter control over your code. Improved debugging tools With Visual Basic 2005, the great gets better. Enhanced debugging tools, including an improved Call Stack display and a Breakpoints window, make it a breeze to hunt down troublesome code. You can even set dif- ferent debugging options (like break or continue) for different types of errors. The return of the “run-edit-and-continue” pattern Visual Basic .NET 1.0 lost the indispensable run-edit-and-continue feature due to the dramatic change in the way .NET applications are compiled (as compared to classic VB). But in the time since, Microsoft has been hard at work on the problem, and starting with Visual Basic 2005 you will once again be able to modify your programs on the fly while you’re run- ning them in the debugger. In fact, in several respects this feature has even been improved from classic VB. bvb_02.book Page 240 Thursday, March 30, 2006 12:39 PM Bug Proofing 241 Understanding Errors Bugs exist in many different varieties—some exotic, others as well known as the common housefly. Some of the species you’ll see include: Editor mistakes Mistyped words and syntax errors are source-code mistakes that are best caught as early as possible. The Visual Basic 2005 editor includes a sophis- ticated error checker that finds these errors as you type. This tool is your first defense against errors, and it’s one of the best ways to catch minor mistakes and save time. Compile-time errors Compile-time errors can result when you ignore an editor mistake, or if you make some other type of error—such as trying to perform a math operation with a string—that may not be caught until the program is being built. When you run a program from the Visual Studio IDE, any compile-time errors are reported to you in the Output window and on the Error List. Runtime errors Runtime errors are problems that occur while the program is being used. Usually, a runtime error is an unhandled error that propagates back to the user and ends the program. For example, if you try to open a file that doesn’t exist and don’t provide any error-handling code, the Common Language Runtime will provide an error message and your code will stop abruptly. A compile-time error usually cannot become a runtime error, because Visual Basic 2005 will refuse to compile the offending code. (When you try to launch it, Visual Studio will explain the problem and give you the option to continue with the previously compiled version of your program.) However, a code statement that is syntactically correct may still result in a runtime problem. For example, trying to access a web page on a computer that may or may not have an Internet connection can cause a runtime error. Logic errors This is the most insidious type of bug, because it is often difficult to determine what part of the code is responsible. Code containing a logic error runs without generating any warning or error messages. However, the information or behavior that results is clearly not what is expected. A good example is an investment program that automatically subtracts 1.5 percent interest on existing balances. Errors that can’t happen One of the goals of the .NET platform is to make your life easier. There are entire classes of errors that have troubled generations of earlier programmers but are now impossible. Memory leaks, pointer errors, and other types of fiendish problems that have plagued our programming ancestors are carefully defended against in the .NET world. bvb_02.book Page 241 Thursday, March 30, 2006 12:39 PM 242 Chapter 8 The Principles of Bug Proofing The following rules will guide you in creating high-quality applications. The earlier an error is detected, the better. You should celebrate when Visual Basic 2005 generates a build error and refuses to compile your code. When a compile-time error occurs, it means that Visual Basic 2005’s automatic error checking has found a potential problem that you’ve missed and has identified it so that you don’t have to spend hours trying to troubleshoot a mystery in the future. Visual Basic 2005 improves on Visual Basic 6 by detecting many common errors earlier—finding missing variables while you type, for instance, instead of when you compile, and flagging data-type conversion problems with compile-time errors before they create runtime errors. Expect the unexpected. Later in this chapter, we’ll consider some basic techniques for coding defensively. Once you start expecting users to enter strange and possibly illogical input, you are ready to prepare and prevent possible catastrophes. Often you can tell the novice programmer from the expert not by how fast an application is completed, but by how well the application stands up after a few months of intensive use in the field. Don’t ignore the compiler. Once your program gets into the hands of users, and inexplicable errors start to occur, a trivial problem that once seemed to be fixed by a ran- domly changed line may keep you awake for a few sleepless nights. Test early and test often. I won’t spend much time in this chapter talking about testing, because it really is a straightforward process. Still, it is amazing how many program- mers don’t try out their own creations, thus missing mistakes that can hurt their pride and careers once they deliver the code. None of the great tools in Visual Basic 2005 can remove the inevitability of human error, so be thorough, and make use of the debugging tools discussed in this chapter. Some programmers even insist that they won’t let any code out of their hands until they’ve single-stepped through every line in every function. Errors at Compile Time Visual Basic 2005’s treatment of errors is straightforward, but slightly differ- ent than in previous releases. In Visual Basic 6, the editor would interrupt you every time you made a mistake with an intrusive message box (as seen in Figure 8-1). Visual Basic 2005 takes a friendlier approach, working as your partner, not your prosecutor. The process works like this: First, if you’ve made an obvious, clear-cut mistake, the editor tries to correct it for you automatically. For example, you’ll notice that if you start an If block and leave out the word Then, the editor will bvb_02.book Page 242 Thursday, March 30, 2006 12:39 PM Bug Proofing 243 add it for you. It will also add certain details (such as the closing End If, in this case) to prevent you from making other possible mistakes. Figure 8-1: The intrusive editor in Visual Basic 6 If the editor can’t correct the mistake, it will underline the offending code. Common reasons for underlining include using a variable, method, or property that’s not defined, calling a method with the wrong number of arguments, or using a language construct with syntax that just doesn’t make sense (for example, writing If End instead of End If). If you have Option Strict enabled (and you should; see the next section for details), invalid variable assignments and conversions will also be highlighted. If you’re wondering why a line is underlined, place the mouse over the line and read the corresponding tooltip text (see Figure 8-2). Figure 8-2: The polite editor in VB 2005 When you compile a program, either for debugging or as a release, any editor errors you’ve ignored will become compile-time errors, and you’ll be asked if you want to continue (Figure 8-3). If you continue, bvb_02.book Page 243 Thursday, March 30, 2006 12:39 PM 244 Chapter 8 your application will not be recompiled, and you’ll end up testing the previously compiled version of your code, without your recent changes. Figure 8-3: A failed build Instead of continuing with compile-time mistakes, you should cancel the build process and review the contents of the Error List window (see Fig- ure 8-4). This window appears automatically when you build an applica- tion that contains at least one compile error. Visual Basic 2005 makes it easy for you: Just double-click on an entry in the Error List, and you’ll be brought to the appropriate spot in your code, with the error high- lighted. This is a big improvement over Visual Basic 6, where you were told about errors one by one, and you had to fix the current error before finding out about the rest. Once you’ve corrected these errors, you can successfully launch your application and get to work. Figure 8-4: Problems in the error list Option Explicit and Option Strict These two lifesaving options should always be enabled. Option Explicit stops you from using a variable without creating it, and thus prevents the mistakes that can occur when a new, empty variable is automatically created after you misspell the name of an existing variable. Option Explicit is enabled by default. Option Strict is new to the .NET versions of Visual Basic. It prevents errors that can result from attempted automatic variable conversions. For example, converting an Int32 into an Int16 is a “narrowing” conversion, and it may or may not succeed. With Option Strict off, you are free to try. . . . bvb_02.book Page 244 Thursday, March 30, 2006 12:39 PM Bug Proofing 245 Option Strict Off Private Sub SwapNumbers(BigNumber As Int32, SmallNumber As Int16) Dim Swap As Int32 Swap = BigNumber ' This is a widening conversion; it always works. BigNumber = SmallNumber ' This is a riskier narrowing conversion. SmallNumber = Swap ' Sure, it works now, but it could become a fatal ' runtime error under the right circumstances. End Sub In this example, Visual Basic won’t complain, and you’ll be blissfully unaware of the potential time bomb—until you submit a value for BigNumber that is larger than 32,767. With Option Strict on, it’s a different story. The code will be underlined, and an error will be generated at compile time. You won’t be allowed to use the code without modifying it to perform an explicit (manual) conversion. At that point, you’ll probably realize the potential problem, and either change SmallNumber to an Int32 or rewrite the code with an extra safeguard: Option Strict On Private Sub SwapNumbers(BigNumber As Int32, SmallNumber As Int16) Dim Swap As Int32 Swap = BigNumber ' This is a widening conversion; it always works. BigNumber = SmallNumber If BigNumber > SmallNumber.MaxValue Then MessageBox.Show "Sorry, this number doesn't fit." Else ' The CType function manually converts the number. SmallNumber = CType(Swap, Int16) End If End Sub This example makes use of the MaxValue constant that is built into many simple data types, including integers. It indicates the largest number that the current variable can hold (which is 32,767 in this case). By using the MaxValue constant, you can avoid coding the number directly into the program, and you allow the program to continue working even if you change the data type of SmallNumber. If you suspect that Option Strict or Option Explicit is not enabled for your project, right-click your project in the Solution Explorer, and select Properties. Now click the Compile tab (shown in Figure 8-5). You can use this tab to set both the Option Strict and Option Explicit settings. You can also bvb_02.book Page 245 Thursday, March 30, 2006 12:39 PM 246 Chapter 8 configure a list of warnings that work in addition to these settings. For exam- ple, you can allow implicit conversions but ask the compiler to warn you when you inadvertently rely on this behavior. Although the Option Explicit and Option Strict settings are the best defense, the warnings are also helpful. In fact, some of the warnings catch potential error conditions that would otherwise pass unnoticed, like declar- ing a variable but not using it, creating a function that doesn’t provide a return value, or creating recursive code (for example, properties that refer to themselves, and are likely to tie your code up in an endless loop of self- referencing). Figure 8-5: Project settings for Option Explicit and Option Strict Line Numbers Line numbers were once the hallmark of old-fashioned programming languages—such as the original DOS version of BASIC. In Visual Basic 6, you were able to optionally add numbers to specific lines. In Visual Basic 2005, you can’t even do that. Line numbers have vanished. Or have they? One well-kept secret is that you can enable a line number display for your code by selecting Tools Options to display the Options window, and then selecting the Text Editor Basic General tab. Click the Line Numbers check box, and Visual Studio will display a margin that numbers every line in the file, including blank ones (see Figure 8-6). bvb_02.book Page 246 Thursday, March 30, 2006 12:39 PM Bug Proofing 247 Figure 8-6: Line numbers return from the past You can’t directly enter or change these numbers. So why use them? As you’ll see later in this chapter, Visual Basic errors include line number infor- mation that pinpoints where an error has occurred. If an unhandled error occurs at a client site, you can customize your error message to display or record the corresponding line number. Then you can track down the corre- sponding code at your desk, without needing to re-create the problem. Visual Studio’s Debugging Tools It’s bound to happen eventually. Illogical data appears. Strange behavior occurs. It looks as though information that you’ve never entered is appearing out of thin air, and code is being executed in a different order or in a differ- ent way than you expected. In other words, you’ve got a bug. So what should you do about it? This section walks you through Visual Basic 2005’s debugging tools, including breakpoints that let you study code flow, watch windows that let you examine variables in action, and the call stack history, which gives additional information about your program’s place in the overall order of procedures. Watching Your Program in Action One of the greatest tools in any programming language is the ability to step through an application. This feature allows you to watch the action and study the flow, or the path, of execution your program takes, through the classes and functions that you provide it with. When you step through your code, you test the assumptions that you have about how it will work. You determine the order in which statements are executed, and the values that are recorded in your variables. Single-stepping allows you to spy on what your program is really up to. bvb_02.book Page 247 Thursday, March 30, 2006 12:39 PM [...]... make XML the native format for all your applications (You won’t learn how to retrieve information from a database yet—that subject is the focus of Chapter 10.) bvb_02 .book Page 272 Thursday, March 30, 20 06 12:39 PM Most of these capabilities aren’t new to the NET Framework However, pre- .NET versions of Visual Basic provided a variety of different ways to access files—some more flexible than others—and... in one of your variables To set a value, double-click the value in the Value column, and type the new value The Immediate Window Longtime Visual Basic developers may remember the Immediate window, which is alive and well in VB 2005 Using the Immediate window, you can dump out the full contents of an object using the Debug.Print command (or the handy question mark shortcut), as shown in Figure 8-1 3 Figure... found that can handle the current error, or until the search reaches the uppermost level of the application—at which point a runtime error will be generated, ending the program 2 56 C h ap te r 8 bvb_02 .book Page 257 Thursday, March 30, 20 06 12:39 PM The Evolution from On Error Goto Up until now, I’ve glossed over an ugly secret Visual Basic 2005 still supports the On Error Goto command for backward compatibility... program to continue and ignore the exception 264 C h ap te r 8 bvb_02 .book Page 265 Thursday, March 30, 20 06 12:39 PM To create an event handler for the UnhandledException event, doubleclick the My Project node in the Solution Explorer, select the Application tab, and then click the View Application Events button in the project properties window The first time you do this, Visual Studio creates a new... application If Visual Basic 2005 tests an assertion and finds out that it is, in fact, false, it will provide an intimidating error message with a pile of diagnostic code, and give you the option to either halt the execution of your program, 266 C h ap te r 8 bvb_02 .book Page 267 Thursday, March 30, 20 06 12:39 PM or ignore the problem and continue Using assertions is a good way to train yourself to look for assumptions... Figure 8-1 1: A Hit Count breakpoint condition B ug Pro ofi ng 251 bvb_02 .book Page 252 Thursday, March 30, 20 06 12:39 PM The Autos, Locals, and Watch Windows When Visual Basic 2005 is in break mode, several additional tabbed windows are provided at the bottom of your screen If any of these is not visible, you can display it using the Debug Windows menu The Autos, Locals, and Watch windows show you the. .. easily find the corresponding problem You can replace the MessageBox.Show() statement in the previous example with the following block of code It reports more information about the exception (see Figure 8-1 7) 258 C h ap te r 8 bvb_02 .book Page 259 Thursday, March 30, 20 06 12:39 PM Dim Spacer As New String( "-" , 150) Spacer = vbNewLine & Spacer & vbNewLine ' Use a StringBuilder, as this is the most efficient... Nothing Then FileStream.Close() ' Close the file End If End Try The foundation of structured error handling is the Try/Catch/Finally block, which replaces certain patterns of use of Goto statements with a more modern structured construct, much as the If/End If or For/ Next statements do In the preceding example, the portion of the code after the Try statement is the code that is being watched for errors... in the Autos, Locals, and Watch windows provides such information as the type or class of the variable or object, and its current value Object Structure One of the most impressive features of the Autos, Locals, and Watch windows is that you can see the object structures of the classes and procedures in your program For example, in the Locals window you’ll see the term Me, which is a reference to the. .. examine the error information in another routine, you’ll find that all of the error information disappears immediately, leaving you empty-handed Visual Basic 2005 exceptions are full-featured objects that you can catch and throw on your own, and pass from routine to routine Language limitations Exceptions are built into the NET runtime This means that you can throw an exception in Visual Basic 2005 and . dif- ferent debugging options (like break or continue) for different types of errors. The return of the “run-edit-and-continue” pattern Visual Basic .NET 1.0 lost the indispensable run-edit-and-continue. Figure 8 -6 ). bvb_02 .book Page 2 46 Thursday, March 30, 20 06 12:39 PM Bug Proofing 247 Figure 8 -6 : Line numbers return from the past You can’t directly enter or change these numbers. So why use them?. from making other possible mistakes. Figure 8-1 : The intrusive editor in Visual Basic 6 If the editor can’t correct the mistake, it will underline the offending code. Common reasons for underlining

Ngày đăng: 13/08/2014, 08:21

TỪ KHÓA LIÊN QUAN