Debugging 101 for Visual Studio
- Sep 15, 2006
Legend has it that the term bug dates from the early days of computers, when a program malfunction was traced to an insect that had flown into the computer and caused a short circuit. Whatever their cause, bugs are something that you certainly don’t want in your applications! This article looks at some common causes of bugs and the tools in Visual Studio that help you to find and exterminate them.
Be aware that a bug is not the same as an exception. An exception (also called a runtime error) is something that, if unhandled, can stop your program dead in its tracks, such as attempting to divide by 0, access a nonexistent drive, or open a file to which you don’t have rights. A bug is a code error that causes your program to behave incorrectly, such as in the following examples:
- A financial program that calculates and displays inaccurate results
- A graphics program that displays elements at the wrong screen location
- Any program that doesn’t respond properly to user input
You may have heard the saying, "An ounce of prevention is worth a pound of cure." This goes for programming, too—the best way to deal with bugs is to avoid them in the first place. This is part of the good programming practice that is second nature to many programmers. Here’s a quick review:
- Use object-oriented programming design as much as possible. The encapsulation provided by classes not only lessens the chance of bugs but makes them easier to find and fix when they do occur.
- For Visual Basic programs, always use Option Explicit so that variable declaration is required. Not doing so is a major cause of bugs.
- Divide your code into relatively small and manageable procedures (methods).
- Use global and public variables only when it’s unavoidable.
- Use the proper data type for your variables. Use of integer types can lead to rounding errors.
No matter how religiously you follow these guidelines, however, you’ll almost surely run into some bugs in the programs you write. Let’s explore how Visual Studio can help you to find and fix those bugs. You’ll see that these tools focus on two main factors that are involved in essentially all bugs: the path of program execution, and the value of variables.