Chapter 9 Trapping Errors by Using Structured Error Handling 237
Exception Description
IOException Occurs when there is an input/output error.
OutOfMemoryException Occurs when there isn’t enough memory.
OverflowException Occurs when an arithmetic-related operation results in an
overflow.
SecurityException Occurs when there is a security-related error.
SqlException Occurs when there is an error when accessing data in Microsoft
SQL Server.
UnauthorizedAccessException Occurs when the operation denies access.
So how do you know which exception types to use? That depends on your code. For
example, in the exercise that we are working on you have been using the System.Drawing
.Bitmap.FromFile method. If you open the Visual Studio Help documentation for FromFile,
you will see an “Exceptions” section.
Tip To quickly open up the Help documentation for FromFile, put your cursor in the FromFile
text in Visual Studio and then press the F1 key. From here, you can open the Image .FromFile
Method (String) topic.
The “Exceptions” section in the Image .FromFile Method (String) topic lists the following
exceptions:
n ArgumentException
n FileNotFoundException
n OutOfMemoryException
With this information in hand, you can write code to handle common exceptions that
take place when a programmer uses FromFile. As you write more code, you will discover
additional Exception objects, and you can also learn about them by using the Help
documentation. Even though there are many different Exception objects, you will use them
in the same way described here and demonstrated below. The following exercise uses two
of the Exception objects above in a Try... Catch error handler to test for more than one
run-time error condition.
Test for multiple run-time error conditions
- In the Button1_Click event procedure, edit the Try... Catch error handler so that it looks
like the following code block. (The original FromFile statement is the same as the code
you used in the previous exercises, but the Catch statements are all new .)
Try
PictureBox1.Image = _
System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")