Processing Errors by Using Try Catch


Processing Errors by Using Try…Catch

A program crash is an unexpected problem in a Visual Basic program from which the program can't recover. You might have experienced your first program crash when Visual Basic couldn't load artwork from a file or in the previous chapter, when you intentionally introduced errors into your program code during debugging. It's not that Visual Basic isn't smart enough to handle the glitch; it's just that Visual Basic hasn't been “told” what to do when something goes wrong.

Fortunately, you don't have to live with occasional errors that cause your programs to crash. You can write special Visual Basic routines, called structured error handlers, to manage and respond to run-time errors before they force the Visual Basic compiler to terminate your program. An error handler handles a run-time error by telling the program how to continue when one of its statements doesn't work. Error handlers can be placed in each event procedure where there is potential for trouble, or in generic functions or subprograms that receive control after an error has occurred and handle the problem systematically. (You'll learn more about writing functions and subprograms in Chapter 10, “Creating Modules and Procedures.”)

Error handlers handle, or trap, a problem by using a Try…Catch code block and a special error handling object named Err. The Err object has a Number property that identifies the error number and a Description property that you can use to display a description of the error. For example, if the run-time error is associated with loading a file from a CD-ROM drive, your error handler might display a custom error message that identifies the problem and prompts the user to insert a CD, rather than allowing the failed operation to crash the program.

When to Use Error Handlers

You can use error handlers in any situation where an action (either expected or unexpected) has the potential to produce an error that stops program execution. Typically, error handlers are used to manage external events that influence a program—for example, events caused by a failed network or Internet connection, a CD or disk not being inserted correctly in the drive, or an offline printer or scanner. The following table lists potential problems that can be addressed by error handlers.

Problem

Description

Network/Internet problems

Network servers, Internet connections, and other resources that fail, or go down, unexpectedly.

Disc drive problems

Unformatted or incorrectly formatted CDs or disks, media that isn't properly inserted, bad sectors, CDs or disks that are full, problems with a CD-ROM drive, and so on.

Path problems

A path to a necessary file that is missing or incorrect.

Printer problems

Printers that are off line, out of paper, out of memory, or otherwise unavailable.

Software not installed

A file or component that your application relies on but that is not installed on the user's computer, or an operating system incompatibility.

Permissions problems

User permissions that are not appropriate for performing a task.

Overflow errors

An activity that exceed the allocated storage space.

Out-of-memory errors

Insufficient application or resource space available in the Microsoft Windows memory management scheme.

Clipboard problems

Problems with data transfer or the Windows Clipboard.

Logic errors

Syntax or logic errors undetected by the compiler and previous tests (such as an incorrectly spelled file name).

Setting the Trap: The Try…Catch Code Block

The code block used to handle a run-time error is called Try…Catch. You place the Try statement in an event procedure right before the statement you're worried about, and the Catch statement follows immediately with a list of the statements that you want to run if a run-time error actually occurs. A number of optional statements, such as Catch When, Finally, Exit Try, and nested Try…Catch code blocks can also be included, as the examples in this chapter will demonstrate. However, the basic syntax for a Try…Catch exception handler is simply the following:

Try     Statements that might produce a run-time error Catch     Statements to run if a run-time error occurs Finally     Optional statements to run whether an error occurs or not End Try

The Try statement identifies the beginning of an error handler in which Try, Catch, and End Try are required keywords, and Finally and the statements that follow are optional. Note that programmers sometimes call the statements between the Try and Catch keywords protected code because any run-time errors resulting from these statements won't cause the program to crash. (Instead, Visual Basic executes the error handling statements in the Catch code block.)

Path and Disc Drive Errors

The following example demonstrates a common run-time error situation—a problem with a path, disc drive, or attached peripheral device. To complete this exercise, you'll load a sample Visual Basic project that I created to show how artwork files are opened in a picture box object on a Windows form.

To prepare for the exercise, insert a blank CD into drive D (or equivalent), and use Windows Explorer or your CD creation software to copy or burn the fileopen.bmp file to it. Alternatively, you can copy the .bmp file to a disk in drive A or another type of removable storage media, such as an attached digital camera, memory stick, or Iomega Zip Drive.

TIP
You'll find the fileopen.bmp file, along with the Disc Drive Error project, in the c:\vb05sbs\chap09 folder.

To complete the exercise, you'll need to be able to remove the CD, or connect and disconnect your external storage device, as test conditions dictate, and you'll need to modify the program code below with the drive letter you're using. You'll use the CD and CD drive (or equivalent media) throughout the chapter to force run-time errors and recover from them.

Experiment with disc drive errors

  1. Insert a blank CD in drive D (or the drive in which you create CDs), and copy the fileopen.bmp file to it.

    Use Windows Explorer or a third-party CD creation program to copy the file and burn the disc. If you're using a different external storage device, connect the device or insert a blank disk, copy fileopen.bmp to it, and make a note of the drive letter Windows assigns to the device.

  2. Start Visual Studio, and then open the Disc Drive Error project, which is located in the c:\vb05sbs\chap09\disc drive error folder.

    The Disc Drive Error project opens in the IDE.

  3. If the project's form isn't visible, display it now.

    The Disc Drive Error project is a skeleton program that displays the fileopen.bmp file in a picture box when the user clicks the Check Drive button. I designed the project as a convenient way to create and trap run-time errors, and you can use it throughout this chapter to build error handlers by using the Try…Catch code block.

  4. Double-click the Check Drive button on the form to display the Button1_Click event procedure.

    You'll see the following line of program code between the Private Sub and End Sub statements:

    PictureBox1.Image = _   System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")

    As you've learned in earlier chapters, the FromFile method opens the specified file. This particular use of FromFile opens the fileopen.bmp file on drive D and displays it in a picture box. However, if the CD is missing, the CD tray is open, the file is not on the CD, or there is another problem with the path or drive letter specified in the code, the statement produces a “File Not Found” error in Visual Basic. This is the run-time error we want to trap.

    NOTE
    If your CD drive or attached peripheral device is using a drive letter other than “D” now, change the drive letter in this program statement to match the letter you're using. For example, a floppy disk drive typically requires the letter “A.” Memory sticks, digital cameras, and other detachable media typically use “E,” “F,” or higher letters for the drive.

  5. With your CD still in drive D or equivalent, click the Start Debugging button on the Standard toolbar to run the program.

    The form for the project appears, as shown here:

    graphic

  6. Click the Check Drive button on the form.

    The program loads the fileopen.bmp file from the CD and displays it in the picture box, as shown here.

    graphic

    The SizeMode property of the picture box object is set to StretchImage, so the file fills the entire picture box object. Now see what happens when the CD isn't in the drive when the program attempts to load the file.

  7. Remove the CD from the drive.

    If you are using a different media type, remove it now. If you are testing with a removable storage device, follow your usual procedure to safely turn it off, and remove the media containing fileopen.bmp.

  8. Click the Check Drive button again on the form.

    The program can't find the file, and Visual Basic issues a run-time error, or unhandled exception, which causes the program to crash. Visual Studio enters debugging mode, highlights the problem statement, and displays the following dialog box:

    graphic

  9. Click the Stop Debugging button on the Standard toolbar to close the program.

    The development environment returns.

An excellent addition to the Visual Studio 2005 software is the very detailed help information (including troubleshooting tips) about the unhandled exception that has stopped our program. But we still need to modify the code to handle this very plausible error scenario in the future.



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net