Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 9 Trapping Errors by Using Structured Error Handling 245


To Do this
Test for specific error
conditions in an event
handler

Use the Catch statement and the appropriate Exception object. For example:
Try
PictureBox1.Image = _
System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")
Catch ex As System.IO.FileNotFoundException 'if File Not Found
MsgBox("Check pathname and disc drive")
Catch ex As OutOfMemoryException 'if Out Of Memory
MsgBox("Is this really a bitmap?", , ex.Message)
Catch ex As Exception
MsgBox("Problem loading file", , ex.Message)
End Try
Create your own
errors in a program

Use the Throw statement. For example, the following code generates
an exception and handles it:
Try
Throw New Exception("There was a problem")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Write nested Try...
Catch error handlers

Place one Try... Catch code block within another. For example:
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
Exit the current Try or
Catch code block

Use the Exit Try statement in the Try or the Catch code block. For example:
If PictureBox1.Enabled = False Then Exit Try
Free download pdf