Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 9 Trapping Errors by Using Structured Error Handling 229


Problem Description
Permissions problems User permissions that are not appropriate for performing a task.
Overflow errors An activity that exceeds 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 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 or DVD into drive D (or equivalent), and use
Windows Explorer or your CD or DVD creation software to copy or burn the Fileopen .bmp
file to it. Alternatively, you can copy the .bmp file to a diskette in drive A or another type of
removable storage media, such as an attached digital camera, memory stick, MP3 player,
or USB flash drive.
Free download pdf