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 |
Test for specific error conditions in an event handler | Use the Catch When syntax and the Err.Number property. For example:
Try PictureBox1.Image = _ System.Drawing.Bitmap.FromFile _ ("d:\fileopen.bmp") Catch When Err.Number = 53 'if File Not Found MsgBox("Check pathname and disc drive") Catch When Err.Number = 7 'if Out Of Memory MsgBox("Is this really a bitmap?", , _ Err.Description) Catch MsgBox("Problem loading file", , _ Err.Description) End Try |
Create your own errors in a program | Use the Err.Raise method. For example, the following code generates a Disc Full error and handles it:
Try Err.Raise(61) 'raise Disc Full error Catch When Err.Number = 61 MsgBox("Error: Disc is full") 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!") 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 |