More Complex Try Catch Error Handlers


More Complex Try…Catch Error Handlers

As your programs become more sophisticated, you might find it useful to write more complex Try…Catch error handlers that manage a variety of run-time errors and unusual error-handling situations. Try…Catch provides for this complexity by:

  • Permitting multiple lines of code in each Try, Catch, or Finally code block.

  • Offering the Catch When syntax, which tests specific error conditions.

  • Allowing nested Try…Catch code blocks, which can be used to build sophisticated and robust error handlers.

In addition, by using a special error-handling object named Err, you can identify and process specific run-time errors and conditions in your program. You'll investigate each of these error-handling features in the following section.

The Err Object

Err is a special Visual Basic object that's assigned detailed error-handling information each time a run-time error occurs. The most useful Err properties for identifying run-time errors are Err.Number and Err.Description. Err.Number contains the number of the most recent run-time error, and Err.Description contains a short error message that matches the run-time error number. By using the Err.Number and Err.Description properties together in an error handler, you can recognize specific errors and respond to them, and you can give the user helpful information about how he or she should respond.

The Err.Number and Err.Description properties contain information about the most recent run-time error.

You can clear the Err object by using the Err.Clear method (which discards previous error information), but if you use the Err object within a Catch code block, clearing the Err object isn't usually necessary because Catch blocks are entered only when a run-time error has just occurred in a neighboring Try code block.

The following table lists many of the run-time errors that Visual Basic applications can encounter. In addition to these error codes, you'll find that some Visual Basic libraries and other components (such as database and system components) provide their own unique error messages, which often can be discovered by using the online Help. Note that despite the error message descriptions, some errors don't appear as you might expect them to, so you'll need to specifically test the error numbers (when possible) by observing how the Err.Number property changes during program execution. Unused error numbers in the range 1–1000 are reserved for future use by Visual Basic.

Error number

Default error message

5

Procedure call or argument is not valid

6

Overflow

7

Out of memory

9

Subscript out of range

11

Division by zero

13

Type mismatch

48

Error in loading DLL

51

Internal error

52

Bad file name or number

53

File not found

55

File already open

57

Device I/O error

58

File already exists

61

Disk full

62

Input past end of file

67

Too many files

68

Device unavailable

70

Permission denied

71

Disk not ready

74

Can't rename with different drive

75

Path/File access error

76

Path not found

91

Object variable or With block variable not set

321

File format is not valid

322

Cannot create necessary temporary file

380

Property value is not valid

381

Property array index is not valid

422

Property not found

423

Property or method not found

424

Object required

429

Cannot create Microsoft ActiveX component

430

Class does not support Automation or does not support expected interface

438

Object does not support this property or method

440

Automation error

460

Clipboard format is not valid

461

Method or data member not found

462

The remote server machine does not exist or is unavailable

463

Class not registered on local machine

481

Picture is not valid

482

Printer error

The following exercise uses the Err.Number and Err.Description properties in a Try…Catch error handler to test for more than one run-time error condition. This capability is made possible by the Catch When syntax, which you'll use to test for specific error conditions in a Try…Catch code block.

Test for multiple run-time error conditions

  1. In the Button1_Click event procedure, edit the Try…Catch error handler so that it looks like the following code block. (The original FromFile statement is the same as the code you used in the previous exercises, but the Catch statements are all new.)

    Try     PictureBox1.Image = _       System.Drawing.Bitmap.FromFile("d:\fileopen.bmp") Catch When Err.Number = 53 'if File Not Found error     MsgBox("Check pathname and disc drive") Catch When Err.Number = 7  'if Out Of Memory error     MsgBox("Is this really a bitmap?", , Err.Description) Catch     MsgBox("Problem loading file", , Err.Description) End Try

    The Catch When syntax is used twice in the error handler, and each time the syntax is used with the Err.Number property to test whether the Try code block produced a particular type of run-time error. If the Err.Number property equals the number 53, the File Not Found run-time error has occurred during the file open procedure, and the message “Check pathname and disc drive” is displayed in a message box. If the Err.Number property is equal to the number 7, an Out of Memory error has occurred—probably the result of loading a file that doesn't actually contain artwork. (I get this error if I accidentally try to open a Microsoft Word document in a picture box object by using the FromFile method.)

    The final Catch statement handles all other run-time errors that could potentially occur during a file-opening process—it's a general “catch-all” code block that prints a general error message inside a message box and a specific error message from the Err.Description property in the title bar of the message box.

  2. Click the Start Debugging button to run the program.

  3. Remove the CD from drive D.

  4. Click the Check Drive button.

    The error handler displays the error message “Check pathname and disc drive” in a message box. The first Check When statement works.

  5. Click OK, and then click Close on the form to end the program.

  6. Insert the CD again, and use Windows Explorer or another tool to copy a second file to the CD that isn't an artwork file. For example, copy a Word document or a Microsoft Excel spreadsheet to the CD.

    You won't open this file in Word or Excel, but you will try to open it (unsuccessfully, we hope) in your program's picture box object. (If your CD-ROM software or drive doesn't allow you to add additional files to a CD after you have burned it, you might need to create a second CD with the two files.)

  7. In the Code Editor, change the name of the fileopen.bmp file in the FromFile program statement to the name of the file (Word, Excel, or other) you copied to the CD in drive D.

    Using a file with a different format gives you an opportunity to test a second type of run-time error—an Out of Memory exception, which occurs when Visual Basic attempts to load a file that isn't a graphic or has too much information for a picture box.

  8. Run the program again, and click the Check Drive button.

    The error handler displays the following error message:

    graphic

    Notice that I have used the Err.Description property to display a short description of the problem (“Out of memory.”) in the message box title bar. Using this property in your error handler can give the user a clearer idea of what has happened.

  9. Click OK, and click Close on the form to stop the program.

  10. Change the file name back to fileopen.bmp in the FromFile method. (You'll use it in the next exercise.)

The Catch When statement is very powerful. By using Catch When in combination with the Err.Number and Err.Description properties, you can write sophisticated error handlers that recognize and respond to several types of exceptions.

Raising Your Own Errors

For testing purposes and other specialized uses, you can artificially generate your own run-time errors in a program with a technique called throwing, or raising, exceptions. To accomplish this, you use the Err.Raise method with one of the error numbers in the table presented earlier. For example, the following syntax uses the Raise method to produce a Disc Full run-time error and then handles the error by using a Catch When statement:

Try     Err.Raise(61) 'raise Disc Full error Catch When Err.Number = 61     MsgBox("Error: Disc is full") End Try

When you learn how to write your own procedures, with this technique you can generate your own errors and return them to the calling routine.

Specifying a Retry Period

Another strategy you can use in an error handler is to try an operation a few times and then disable it if the problem isn't resolved. For example, in the following exercise, a Try…Catch block employs a counter variable named Retries to track the number of times the message “Please insert the disc in drive D!” is displayed, and after the second time, the error handler disables the Check Drive button. The trick to this technique is declaring the Retries variable at the top of the form's program code so that it has scope throughout all of the form's event procedures. The Retries variable is then incremented and tested in the Catch code block. The number of retries can be modified by simply changing the “2” in the statement, as shown here:

If Retries <= 2

Use a variable to track run-time errors

  1. In the Code Editor, scroll to the top of the form's program code, and directly below the Public Class Form1 statement, type the following variable declaration:

    Dim Retries As Short = 0

    Retries is declared as a Short integer variable because it won't contain very big numbers. It's assigned an initial value of 0 so that it resets properly each time the program runs.

  2. In the Button1_Click event procedure, edit the Try…Catch error handler so that it looks like the following code block:

    Try     PictureBox1.Image = _       System.Drawing.Bitmap.FromFile("d:\fileopen.bmp") Catch     Retries += 1     If Retries <= 2 Then         MsgBox("Please insert the disc in drive D!")     Else         MsgBox("File Load feature disabled")         Button1.Enabled = False     End If End Try

    The Try block tests the same file-opening procedure, but this time, if an error occurs, the Catch block increments the Retries variable and tests the variable to be sure that it's less than or equal to 2. The number 2 can be changed to allow any number of retries—currently it allows only two run-time errors. After two errors, the Else clause is executed, and a message box appears indicating that the file-loading feature has been disabled. The Check Drive button is then disabled—in other words, grayed out and rendered unusable for the remainder of the program.

    TIP
    This revised version of the error handler that you have been building has been renamed Disc Drive Handler and is stored in the c:\vb05sbs\chap09\disc drive handler folder.

  3. Click the Start Debugging button to run the program.

  4. Remove the CD from drive D.

  5. Click the Check Drive button.

    The error handler displays the error message “Please insert the disc in drive D!” in a message box, as shown here. Behind the scenes, the Retries variable is also incremented to 1.

    graphic

  6. Click OK, and then click the Check Drive button again.

    The Retries variable is set to 2, and the message “Please insert the disc in drive D!” appears again.

  7. Click OK, and then click the Check Drive button a third time.

    The Retries variable is incremented to 3, and the Else clause is executed. The message “File Load feature disabled” appears, as shown here:

    graphic

  8. Click OK in the message box.

    The Check Drive button is disabled on the form, as shown here:

    graphic

    The error handler has responded to the disc drive problem by allowing the user a few tries to fix the problem, and then it has disabled the problematic button. (In other words, the user can no longer click the button.) This disabling action stops future run-time errors, although the program might no longer function exactly as it was originally designed.

  9. Click the Close button to stop the program.

Using Nested Try…Catch Blocks

You can also use nested Try…Catch code blocks in your error handlers. For example, the following disc drive error handler uses a second Try…Catch block to retry the file open operation a single time if the first attempt fails and generates a run-time error:

Try     PictureBox1.Image = _       System.Drawing.Bitmap.FromFile("d:\fileopen.bmp") Catch     MsgBox("Insert the disc in drive D, then click OK!")     Try         PictureBox1.Image = _           System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")     Catch         MsgBox("File Load feature disabled")         Button1.Enabled = False     End Try End Try

If the user inserts the disc in the drive as a result of the message prompt, the second Try block opens the file without error. However, if a file-related run-time error still appears, the second Catch block displays a message saying that the file load feature is being disabled, and the button is disabled.

In general, nested Try…Catch error handlers work well as long as you don't have too many tests or retries to manage. If you do need to retry a problematic operation many times, use a variable to track your retries, or develop a function containing an error handler that can be called repeatedly from your event procedures. (See Chapter 10, “Creating Modules and Procedures,” for more information about creating functions.)



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