Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

244 Part II Programming Fundamentals


Using the Exit Try syntax, you can jump completely out of the current Try or Catch code
block. If there’s a Finally code block, this code will be executed, but Exit Try lets you jump
over any remaining Try or Catch statements you don’t want to execute.
The following sample routine shows how the Exit Try statement works. It first checks to
see whether the Enabled property of the PictureBox1 object is set to False, a flag that
might indicate that the picture box isn’t ready to receive input. If the picture box isn’t yet
enabled, the Exit Try statement skips to the end of the Catch code block, and the file load
operation isn’t attempted.
Try
If PictureBox1.Enabled = False Then Exit 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 example builds on the last error handler that you experimented with in this chapter
(the Disc Drive Handler project). If you’d like to test the Exit Try statement in the context of
that program, open the Disc Drive Handler project and enter the If statement that contains
the Exit Try in the Code Editor. You’ll also need to use the Properties window to disable the
picture box object on the form (in other words, to set its Enabled property to False).
Congratulations! You’ve learned a number of important fundamental programming
techniques in Visual Basic, including how to write error handlers. Now you’re ready to
increase your programming efficiency by learning to write Visual Basic modules and
procedures.

Chapter 9 Quick Reference


To Do this
Detect and process
run-time errors

Build an error handler by using one or more Try... Catch code blocks.
For example, the following error handler code tests for path or disc drive
problems:
Try
PictureBox1.Image = _
System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")
Catch
MsgBox("Check path or insert disc")
Finally
MsgBox("Error handler complete")
End Try
Free download pdf