Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))

Chapter 9

Trapping Errors by Using Structured Error Handling

After completing this chapter, you will be able to:

In Chapter 8, “Debugging Visual Basic Programs,” you learned how to recognize run-time errors in a Microsoft Visual Basic program and how to locate logic errors and other defects in your program code by using the Microsoft Visual Studio 2005 debugging tools. In this chapter, you'll learn how to build blocks of code that handle run-time errors, also referred to as exceptions, which occur as a result of normal operating conditions—for example, errors due to a CD not being in a drive, a lost Internet connection, or an offline printer. These routines are called structured error handlers (or structured exception handlers), and you can use them to recognize run-time errors as they occur in a program, suppress unwanted error messages, and adjust program conditions so that your application can regain control and run again.

Fortunately, Visual Basic offers the powerful Try…Catch code block for handling errors. In this chapter, you'll learn how to trap run-time errors by using Try…Catch code blocks, and you'll learn how to use the Err.Number and Err.Description properties to identify specific run-time errors. You'll also learn how to use multiple Catch statements to write more flexible error handlers, build nested Try…Catch code blocks, and use the Exit Try statement to exit a Try…Catch code block prematurely. The programming techniques you'll learn were added to Visual Basic with Microsoft Visual Studio .NET versions 2002 and 2003, and they are similar to the structured error handlers provided by the most advanced programming languages, such as Java and C++. The most reliable, or robust, Visual Basic programs make use of several error handlers to manage unforeseen circumstances and provide users with consistent and trouble-free computing experiences.

Upgrade Notes: Migrating Visual Basic 6 Code to Visual Basic 2005

If you're experienced with Microsoft Visual Basic 6, you'll notice some new features in Microsoft Visual Basic 2005, including the following:

Категории