Chapter 9 Trapping Errors by Using Structured Error Handling 245
To Do this
Test for specific error
conditions in an event
handlerUse 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 programUse 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 handlersPlace 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 blockUse the Exit Try statement in the Try or the Catch code block. For example:
If PictureBox1.Enabled = False Then Exit Try