238 Part II Programming Fundamentals
Catch ex As System.IO.FileNotFoundException 'if File Not Found error
MsgBox("Check pathname and disc drive")
Catch ex As OutOfMemoryException 'if Out Of Memory error
MsgBox("Is this really a bitmap?", , ex.Message)
Catch ex As Exception
MsgBox("Problem loading file", , ex.Message)
End Try
This code has three Catch statements. If the FileNotFoundException occurs during the
file open procedure, the message “Check pathname and disc drive” is displayed in
a message box. If the OutOfMemoryException occurs—probably the result of loading
a file that doesn’t actually contain artwork—the message “Is this really a bitmap?” is
displayed. (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 Message property in the title bar of the message box.
- Click the Start Debugging button to run the program.
- Remove the CD or DVD from drive D.
- Click the Check Drive button.
The error handler displays the error message “Check pathname and disc drive” in a
message box. The first Catch statement works.
- Click OK, and then click the Close button on the form to end the program.
- Insert the CD or DVD again, and then use Windows Explorer or another tool to
copy a second file to the CD or DVD that isn’t an artwork file. For example, copy
a Word document or a Microsoft Excel spreadsheet to the CD or DVD.
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 or DVD software or drive
doesn’t allow you to add additional files to a CD or DVD after you have burned it, you
might need to create a second CD or DVD with the two files .) - 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 or DVD
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.