Finding the Errors: Introduction to Visual Basic Debugging
In this lesson, you will learn about fixing program errors through debugging.
No matter how carefully you design a program or write code, errors are bound to happen. Sometimes errors keep the program from even starting, sometimes they cause the program to stop running or crash, and other times, the program may run but not give the expected results.
Of course, when errors do occur, you will want to find them and fix them. Errors in a program are commonly known as bugs, and the process of finding them and fixing them is known as debugging.
The process of debugging is iterative—that is, it is a process you will repeat over and over again. Typically you will write some code, run the program until an error occurs, find the bug, fix it, and then run the program again.
In most cases, you do not need to stop the program to fix it. You can fix the code where the error occurred and keep running the program where you left off; this process is called Edit and Continue.
Debugging is done in the Visual Basic IDE (integrated development environment)—which contains several special commands and windows to help you find bugs. You will learn more about these in the following lessons.
This example involves an exception. Exceptions are objects that get created (and thrown) when the program realizes that an error has occurred. Different types of exceptions are created, depending on the type of error that has occurred. Under the default user settings, if an exception occurs while running your Visual Basic program, a dialog box appears to explain the error and help you fix it.
To use edit and continue
On the File menu, select New Project.
On the Templates pane in the New Project dialog box, click Windows Application.
In the Name box, type Edit and then click OK.
A new Windows Forms project opens.
Double-click the form to open the Code Editor.
In the Form_Load event handler, add the following code.
Press F5 to run the program. The program will halt and an exception dialog box is shown with the message "InvalidCastException was unhandled".
The exception occurred because there is a typographical error in the code. The wrong variable was used—it should be number, the Integer variable, not numbers, which is a String variable.
Notice that the program is still running; it is just in the debugging break mode. Using Edit and Continue, you can fix the error without having to stop the program (and re-running to check it).
In the Code Editor, change numbers + 1 to number + 1.
Press F5 to continue. A message box with the number 2 should appear.