Visual Basic 2005


Add to MY Favorites...

Back to Vicky's Home Page Teaching Home Page Visual Basic 2005 Html For Kids

Handling Errors

Code modules can be written to handle expected run time errors, such as the file is not found, the CD is not in the drive or the printer is not turned on.

Several new statements are included with Visual Basic 2005; Try…Catch, Catch..When and Exit try. The Err.Number property and Err.Description property remain from the previous versions. 

Try…Catch

Provides code for when something goes wrong. The try statements would be the ones where you are concerned a run-time error could occur.

Think about statements which require peripheral resources such as files where you could have a drive, path, file, network connections or permission problems and printers, where the printer could be turned off.  Other potential errors to prepare for are overflow errors, out of memory errors and clipboard problems

 Syntax

Try

     Statements that might produce a run-time error

Catch

     Statements to run if a run-time error occurs

Finally

     Statements to run whether an error occurs or not

End Try

 Example: 

Try

     Picturebox1.Image = _

     System.Drawing.Bitmap.FromFile(“d:\file.jpg”)

Catch

MsgBox(“There is no disk in drive D”)

Finally

MsgBox(“Disk error handler complete”)

End Try

 Note: The Finally clause is optional.

 

Catch When

Use Catch When to test for more than one error condition, using the Err.Number property.  This property is assigned a value by Visual Basic when a run-time error occurs.  A corresponding Err.Description is available to use with the Err.Number, to display an error message.

 Syntax: 

Try

     Statements that might produce a run-time error

Catch when

     Statements to run if a run-time error occurs

Catch when

     Statements to run if a run-time error occurs

Catch

     Statements to run for all other errors

End Try

 

The Catch when is used with Err.Number and Err.Description properties.

Example:

Try

     Picturebox1.Image = _

     System.Drawing.Bitmap.FromFile(“d:\file.jpg”)

Catch when Err.Number = 53 ‘file not found error

     msgBpx(Err.Decription)

Catch when Err.Number = 7 ‘out of memory error

     msgBpx(Err.Decription)

Catch

     msgBpx(“Problemk loading file”)

End Try

 

Allow a Retry

Include an If statement and a MsgBox to give the use a chance, or two, to correct the error condition.

 Example:

Try

     Picturebox1.Image = _

     System.Drawing.Bitmap.FromFile(“d:\file.jpg”)

Catch

     Retries +=1

     If retries <= 2 then

     MsgBox(“Please insert the disk in drive D”)

     Else

         MsgBox(“File load has been disabled”)

         Button1.Enabled = False

     End If

End Try

 


 
Another page developed by
vicky@vickywoodard.com
Copyright © 2006 Vicky K. Woodard
All rights reserved
Last updated: 8/17/2006